Tom
Tom

Reputation: 802

Extracting data from indexPathsForSelectedRows() - SWIFT

I'm trying to extract all data from selected rows in my table. I use the following code to print the indexPaths. But what do I have to do to print out the text from the selected rows?

     let indexPaths:NSArray = tableView.indexPathsForSelectedRows()!


            `for var i = 0; i < indexPaths.count; ++i {

            var thisPath:NSIndexPath = indexPaths.objectAtIndex(i) as NSIndexPath

            println("row = \(thisPath.row) and section = \(thisPath.section)")
       }

Prints to console the selected rows

row = 1 and section = 0
row = 3 and section = 0

row = 6 and section = 0

Upvotes: 0

Views: 3976

Answers (1)

Antonio
Antonio

Reputation: 72750

You can use the cellForRowAtIndexPath method of UITableView to obtain a cell by index path:

if let indexPaths = tableView.indexPathsForSelectedRows() {
    for var i = 0; i < indexPaths.count; ++i {

        var thisPath = indexPaths[i] as NSIndexPath
        var cell = tableView.cellForRowAtIndexPath(thisPath)
        if let cell = cell {
            // Do something with the cell
            // If it's a custom cell, downcast to the proper type
        }
    }
}

Note that indexPathsForSelectedRows returns an optional (nil when no row is selected), so it's better to protect it with an optional binding to prevent runtime exceptions.

Upvotes: 3

Related Questions