如何知道是否选择了 UITableView 的单元格? [英] How can I know if a cell of UITableView is selected?

查看:24
本文介绍了如何知道是否选择了 UITableView 的单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 XCode 用 Swift 编写一个应用程序.它包括一个 UITableView.只有一个问题 - 在 Swift 中,我如何知道用户选择了哪个单元格?

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?

澄清:

  1. 用户选择了标签为foo"的单元格
  2. 代码应返回foo"或用户选择的任何内容

推荐答案

您可以通过在视图控制器中添加以下函数来判断用户选择了哪个单元格.

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

...

}

所以现在取决于您是否有一个数组来显示每个单元格的文本名称.如果是,您可以使用此 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])")
}

这篇关于如何知道是否选择了 UITableView 的单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆