如何在swift中获取选定行的文本标签?

时间:2021-05-19 10:43:53

So i am trying to get the value of the textLabel of the row I select. I tried printing it, but it didn't work. After some research I found out that this code worked, but only in Objective-C;

我想要得到我选择的行的textLabel的值。我试着打印它,但没有成功。经过一些研究,我发现这个代码只在Objective-C中有效;

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath    *)indexPath
    {
        NSLog(@"did select  and the text is %@",[tableView cellForRowAtIndexPath:indexPath].textLabel.text);]
    }

I could not find any solution for Swift. Printing the indexpath.row is possible though, but that is not what I need.

我找不到斯威夫特的解决办法。印刷indexpath。行是可能的,但这不是我需要的。

so what should I do? or what is the 'Swift-version' of this code?

那么我该怎么做呢?或者这个代码的“迅捷版本”是什么?

8 个解决方案

#1


93  

Try this:

试试这个:

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


13  

If you're in a class inherited from UITableViewController, then this is the swift version:

如果你的类继承自UITableViewController,那么这就是swift版本:

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    let cell = self.tableView.cellForRowAtIndexPath(indexPath)
    NSLog("did select and the text is \(cell?.textLabel?.text)")
}

Note that cell is an optional, so it must be unwrapped - and the same for textLabel. If any of the 2 is nil (unlikely to happen, because the method is called with a valid index path), if you want to be sure that a valid value is printed, then you should check that both cell and textLabel are both not nil:

注意,单元格是可选的,因此它必须被打开——textLabel也是如此。如果2中的任何一个是nil(不太可能发生,因为这个方法是用有效的索引路径调用的),如果您想确保打印了一个有效的值,那么您应该检查单元格和textLabel都不是nil:

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


1  

If you want to print the text of a UITableViewCell according to its matching NSIndexPath, you have to use UITableViewDelegate's tableView:didSelectRowAtIndexPath: method and get a reference of the selected UITableViewCell with UITableView's cellForRowAtIndexPath: method.

如果您想根据UITableViewCell的匹配NSIndexPath打印文本,您必须使用UITableViewDelegate的tableView:didSelectRowAtIndexPath:方法,并使用UITableView的cellForRowAtIndexPath:方法获取选定的UITableViewCell的引用。

For example:

例如:

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
    }

}

However, for many reasons, I would not encourage you to use the previous code. Your UITableViewCell should only be responsible for displaying some content given by a model. In most cases, what you want is to print the content of your model (could be an Array of String) according to a NSIndexPath. By doing things like this, you will separate each element's responsibilities.

但是,出于许多原因,我不鼓励您使用前面的代码。UITableViewCell应该只负责显示模型给出的一些内容。在大多数情况下,您想要的是根据NSIndexPath打印模型的内容(可以是字符串数组)。通过这样做,您将分离每个元素的职责。

Thereby, this is what I would recommend:

因此,我建议如下:

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
    }

}

As you can see, with this code, you don't have to deal with optionals and don't even need to get a reference of the matching UITableViewCell inside tableView:didSelectRowAtIndexPath: in order to print the desired text.

正如您所看到的,使用这段代码,您不必处理选项,甚至不需要在tableView:didSelectRowAtIndexPath:中获取匹配的UITableViewCell的引用,以便打印所需的文本。

#4


1  

Swift 3

斯威夫特3

To get the label of the selected row:

获取所选行的标签:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let cell = tableView.cellForRow(at: indexPath) as! TableViewCell

    print(cell.textLabel?.text)
}

To get the label of the deselected row:

获得被取消选举的行的标签:

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {

    let cell = tableView.cellForRow(at: indexPath) as! TableViewCell

    print(cell.textLabel?.text)
}

#5


1  

Swift 3

斯威夫特3

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let indexPath = tableView.indexPathForSelectedRow
    let currentCell = tableView.cellForRow(at: indexPath!)!
    print(currentCell.textLabel!.text)
}

#6


1  

In my case I made small changes, when i search the value in tabelview select (didSelectRowAtIndexPath) the cell its return the index of the cell so im get problem in move one viewControler to another.By using this method i found a solution to redirect to a new viewControler

在我的例子中,我做了一些小的修改,当我在tabelview select (didSelectRowAtIndexPath)中搜索值时,单元格返回单元格的索引,因此我在将一个viewControler移动到另一个单元格时遇到了问题。通过使用这个方法,我找到了一个重新定向到新的viewControler的解决方案

let indexPath = tableView.indexPathForSelectedRow!
let currentCellValue = tableView.cellForRow(at: indexPath!)! as UITableViewCell
let textLabelText = currentCellValue.textLabel!.text
print(textLabelText) 

#7


0  

Maintain an array which stores data in the cellforindexPath method itself :-

维护一个在cellforindexPath方法本身中存储数据的数组:-

[arryname objectAtIndex:indexPath.row];

Using same code in the didselectaAtIndexPath method too.. Good luck :)

在didselectaAtIndexPath方法中也使用相同的代码。祝你好运:)

#8


0  

This will work:

这将工作:

let item = tableView.cellForRowAtIndexPath(indexPath)!.textLabel!.text!

#1


93  

Try this:

试试这个:

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


13  

If you're in a class inherited from UITableViewController, then this is the swift version:

如果你的类继承自UITableViewController,那么这就是swift版本:

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    let cell = self.tableView.cellForRowAtIndexPath(indexPath)
    NSLog("did select and the text is \(cell?.textLabel?.text)")
}

Note that cell is an optional, so it must be unwrapped - and the same for textLabel. If any of the 2 is nil (unlikely to happen, because the method is called with a valid index path), if you want to be sure that a valid value is printed, then you should check that both cell and textLabel are both not nil:

注意,单元格是可选的,因此它必须被打开——textLabel也是如此。如果2中的任何一个是nil(不太可能发生,因为这个方法是用有效的索引路径调用的),如果您想确保打印了一个有效的值,那么您应该检查单元格和textLabel都不是nil:

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


1  

If you want to print the text of a UITableViewCell according to its matching NSIndexPath, you have to use UITableViewDelegate's tableView:didSelectRowAtIndexPath: method and get a reference of the selected UITableViewCell with UITableView's cellForRowAtIndexPath: method.

如果您想根据UITableViewCell的匹配NSIndexPath打印文本,您必须使用UITableViewDelegate的tableView:didSelectRowAtIndexPath:方法,并使用UITableView的cellForRowAtIndexPath:方法获取选定的UITableViewCell的引用。

For example:

例如:

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
    }

}

However, for many reasons, I would not encourage you to use the previous code. Your UITableViewCell should only be responsible for displaying some content given by a model. In most cases, what you want is to print the content of your model (could be an Array of String) according to a NSIndexPath. By doing things like this, you will separate each element's responsibilities.

但是,出于许多原因,我不鼓励您使用前面的代码。UITableViewCell应该只负责显示模型给出的一些内容。在大多数情况下,您想要的是根据NSIndexPath打印模型的内容(可以是字符串数组)。通过这样做,您将分离每个元素的职责。

Thereby, this is what I would recommend:

因此,我建议如下:

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
    }

}

As you can see, with this code, you don't have to deal with optionals and don't even need to get a reference of the matching UITableViewCell inside tableView:didSelectRowAtIndexPath: in order to print the desired text.

正如您所看到的,使用这段代码,您不必处理选项,甚至不需要在tableView:didSelectRowAtIndexPath:中获取匹配的UITableViewCell的引用,以便打印所需的文本。

#4


1  

Swift 3

斯威夫特3

To get the label of the selected row:

获取所选行的标签:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let cell = tableView.cellForRow(at: indexPath) as! TableViewCell

    print(cell.textLabel?.text)
}

To get the label of the deselected row:

获得被取消选举的行的标签:

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {

    let cell = tableView.cellForRow(at: indexPath) as! TableViewCell

    print(cell.textLabel?.text)
}

#5


1  

Swift 3

斯威夫特3

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let indexPath = tableView.indexPathForSelectedRow
    let currentCell = tableView.cellForRow(at: indexPath!)!
    print(currentCell.textLabel!.text)
}

#6


1  

In my case I made small changes, when i search the value in tabelview select (didSelectRowAtIndexPath) the cell its return the index of the cell so im get problem in move one viewControler to another.By using this method i found a solution to redirect to a new viewControler

在我的例子中,我做了一些小的修改,当我在tabelview select (didSelectRowAtIndexPath)中搜索值时,单元格返回单元格的索引,因此我在将一个viewControler移动到另一个单元格时遇到了问题。通过使用这个方法,我找到了一个重新定向到新的viewControler的解决方案

let indexPath = tableView.indexPathForSelectedRow!
let currentCellValue = tableView.cellForRow(at: indexPath!)! as UITableViewCell
let textLabelText = currentCellValue.textLabel!.text
print(textLabelText) 

#7


0  

Maintain an array which stores data in the cellforindexPath method itself :-

维护一个在cellforindexPath方法本身中存储数据的数组:-

[arryname objectAtIndex:indexPath.row];

Using same code in the didselectaAtIndexPath method too.. Good luck :)

在didselectaAtIndexPath方法中也使用相同的代码。祝你好运:)

#8


0  

This will work:

这将工作:

let item = tableView.cellForRowAtIndexPath(indexPath)!.textLabel!.text!