How to get textLabel of selected row in swift?

2019-01-17 15:00发布

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;

    - (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.

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

10条回答
叼着烟拽天下
2楼-- · 2019-01-17 15:25

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

let indexPath = tableView.indexPathForSelectedRow!
let currentCellValue = tableView.cellForRow(at: indexPath!)! as UITableViewCell
let textLabelText = currentCellValue.textLabel!.text
print(textLabelText) 
查看更多
欢心
3楼-- · 2019-01-17 15:34

In swift 4 : by overriding method

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let storyboard = UIStoryboard(name : "Main", bundle: nil)
        let next vc = storyboard.instantiateViewController(withIdentifier: "nextvcIdentifier") as! NextViewController

       self.navigationController?.pushViewController(prayerVC, animated: true)
}
查看更多
地球回转人心会变
4楼-- · 2019-01-17 15:34

I'm used the following way, and its working fine :-

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

     let cell = tableView.cellForRow(at: indexPath)
     cell?.textLabel?.text = "Selected Row"
}
查看更多
成全新的幸福
5楼-- · 2019-01-17 15:36

This will work:

let item = tableView.cellForRowAtIndexPath(indexPath)!.textLabel!.text!
查看更多
登录 后发表回答