Как получить textLabel выбранной строки в swift?
Итак, я пытаюсь получить значение textLabel строки, которую я выбираю. Я попробовал распечатать его, но это не сработало. После некоторых исследований выяснилось, что этот код работал, но только в Objective-C;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"did select and the text is %@",[tableView cellForRowAtIndexPath:indexPath].textLabel.text);]
}
Я не мог найти решение для Swift. Возможно, печать indexpath.row возможна, но это не то, что мне нужно.
так что мне делать? или что такое "Swift-версия" этого кода?
Ответы
Ответ 1
Попробуйте следующее:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let indexPath = tableView.indexPathForSelectedRow() //optional, to get from any UIButton for example
let currentCell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell
print(currentCell.textLabel!.text)
Ответ 2
Если вы находитесь в классе, унаследованном от UITableViewController
, то это быстрая версия:
override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
let cell = self.tableView.cellForRowAtIndexPath(indexPath)
NSLog("did select and the text is \(cell?.textLabel?.text)")
}
Обратите внимание, что cell
является необязательным, поэтому он должен быть развернут - и то же самое для textLabel
. Если какой-либо из двух значений равен нулю (маловероятно, потому что метод вызывается с допустимым указательным путем), если вы хотите убедиться, что напечатанное значение напечатано, тогда вы должны проверить, что оба cell
и textLabel
оба не ноль:
override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
let cell = self.tableView.cellForRowAtIndexPath(indexPath)
let text = cell?.textLabel?.text
if let text = text {
NSLog("did select and the text is \(text)")
}
}
Ответ 3
Если вы хотите напечатать текст UITableViewCell
в соответствии с его соответствием NSIndexPath
, вы должны использовать метод UITableViewDelegate
tableView:didSelectRowAtIndexPath:
и получить ссылку на выбранный UITableViewCell
с помощью UITableView
cellForRowAtIndexPath:
.
Например:
import UIKit
class TableViewController: UITableViewController {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
switch indexPath.row {
case 0: cell.textLabel?.text = "Bike"
case 1: cell.textLabel?.text = "Car"
case 2: cell.textLabel?.text = "Ball"
default: cell.textLabel?.text = "Boat"
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedCell = tableView.cellForRowAtIndexPath(indexPath)
print(selectedCell?.textLabel?.text)
// this will print Optional("Bike") if indexPath.row == 0
}
}
Однако, по многим причинам, я бы не рекомендовал использовать предыдущий код. Ваш UITableViewCell
должен отвечать только за отображение некоторого содержимого, заданного моделью. В большинстве случаев, вы хотите напечатать содержимое своей модели (может быть Array
of String
) в соответствии с NSIndexPath
. Выполняя подобные действия, вы будете разделять обязанности каждого элемента.
Таким образом, это то, что я бы рекомендовал:
import UIKit
class TableViewController: UITableViewController {
let toysArray = ["Bike", "Car", "Ball", "Boat"]
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return toysArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = toysArray[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let toy = toysArray[indexPath.row]
print(toy)
// this will print "Bike" if indexPath.row == 0
}
}
Как вы можете видеть, с помощью этого кода вам не нужно иметь дело с опциями и даже не нужно получать ссылку на соответствие UITableViewCell
внутри tableView:didSelectRowAtIndexPath:
, чтобы напечатать нужный текст.
Ответ 4
В моем случае я сделал небольшие изменения, когда я просматриваю значение в tabelview select (didSelectRowAtIndexPath
), ячейка возвращает индекс ячейки, поэтому im get problem при перемещении одного viewControler в другой. Используя этот метод, я нашел решение для перенаправления на новый viewControler
let indexPath = tableView.indexPathForSelectedRow!
let currentCellValue = tableView.cellForRow(at: indexPath!)! as UITableViewCell
let textLabelText = currentCellValue.textLabel!.text
print(textLabelText)
Ответ 5
Swift 3
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indexPath = tableView.indexPathForSelectedRow
let currentCell = tableView.cellForRow(at: indexPath!)!
print(currentCell.textLabel!.text)
}
Ответ 6
Поддерживать массив, который хранит данные в самом методе cellforindexPath
: -
[arryname objectAtIndex:indexPath.row];
Использование того же кода в методе didselectaAtIndexPath
тоже.. Удачи:)
Ответ 7
Это будет работать:
let item = tableView.cellForRowAtIndexPath(indexPath)!.textLabel!.text!
Ответ 8
Swift 3
Чтобы получить метку строки выбрана:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! TableViewCell
print(cell.textLabel?.text)
}
Чтобы получить метку строки отменил выбор:
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! TableViewCell
print(cell.textLabel?.text)
}