[uitableview] How to get textLabel of selected row in swift?

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?

This question is related to uitableview swift ios8 tableview xcode6

The answer is


Swift 4

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)
}

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

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:

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)")
    }
}

This will work:

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

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) 

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

[arryname objectAtIndex:indexPath.row];

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


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.

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.

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.


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)
}

Examples related to uitableview

Adding a UISegmentedControl to UITableView make UITableViewCell selectable only while editing How to fix Error: this class is not key value coding-compliant for the key tableView.' UITableView example for Swift Swift - how to make custom header for UITableView? How to insert new cell into UITableView in Swift How to detect tableView cell touched or clicked in swift Dynamic Height Issue for UITableView Cells (Swift) UIButton action in table view cell How to get the indexpath.row when an element is activated?

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Examples related to ios8

Is there any way to show a countdown on the lockscreen of iphone? How to display an activity indicator with text on iOS 8 with Swift? How to call gesture tap on UIView programmatically in swift Changing the Status Bar Color for specific ViewControllers using Swift in iOS8 Can I set the cookies to be used by a WKWebView? UIAlertController custom font, size, color How to force view controller orientation in iOS 8? How to get textLabel of selected row in swift? Launch Image does not show up in my iOS App NavigationBar bar, tint, and title text color in iOS 8

Examples related to tableview

How to get textLabel of selected row in swift? JavaFX 2.1 TableView refresh items Changing background color of selected cell?

Examples related to xcode6

'Framework not found' in Xcode No suitable records were found verify your bundle identifier is correct unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard Move a view up only when the keyboard covers an input field My prerelease app has been "processing" for over a week in iTunes Connect, what gives? Programmatically navigate to another view controller/scene Changing the Status Bar Color for specific ViewControllers using Swift in iOS8 Change tab bar item selected color in a storyboard How do I change UIView Size? How to get textLabel of selected row in swift?