问题
I am writing an app in Swift with XCode. It includes a UITableView
. Just one question - in Swift, how can I tell what cell is selected by the user?
To clarify:
- A user selects the cell with the label "foo"
- The code should return "foo", or whatever is selected by the user
回答1:
You can tell what cell is selected by User by adding following function in your view controller.
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
...
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
println("You selected cell #\(indexPath.row)!")
}
...
}
So now it depends that whether you are having an array to display the text names of each cell. If yes you can use this indexPath.row to retrieve the text of the row user selected.
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView : UITableView!
var data:String[] = ["Cell 1","Cell 2","Cell 3","Cell 4"]
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell : UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell
cell.text = self.data[indexPath.row]
return cell
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
println("SELECTED INDEX /(indexPath.row)")
println("Selected Cell Text /(data[indexPath.row])")
}
回答2:
Assuming you have the indexPath of the cell in question - eg from within any of your UITableViewDelegate or UITableViewDataSource methods,
BOOL selected = [tableView.indexPathsForSelectedRows containsObject:indexPath];
来源:https://stackoverflow.com/questions/26318229/how-can-i-know-if-a-cell-of-uitableview-is-selected