繁体   English   中英

我如何知道是否选择了UITableView的单元格?

[英]How can I know if a cell of UITableView is selected?

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

澄清:

  1. 用户选择带有标签“ foo”的单元格
  2. 代码应返回“ foo”,或用户选择的任何内容

假设您有相关单元格的indexPath-例如,从任何UITableViewDelegate或UITableViewDataSource方法中,

BOOL selected = [tableView.indexPathsForSelectedRows containsObject:indexPath];

您可以通过在视图控制器中添加以下功能来告诉用户选择了哪个单元格。

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
...

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    println("You selected cell #\(indexPath.row)!")
}

...

}

因此,现在取决于是否要使用一个数组来显示每个单元格的文本名称。 如果是,则可以使用此indexPath.row检索所选行用户的文本。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM