2014-10-30 51 views
8

我正在使用Swift创建一个应用程序。 我有一个UITableView,我用来自数据库的一些数据填充。当用户点击一个单元格时,我想触发一个动作。当用户点击一个单元格时触发一个动作

我做了什么:

var array: [String] = ["example"] 


    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return array.count 
    } 



    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     var cell = UITableViewCell(style :UITableViewCellStyle.Default, reuseIdentifier: "cell") 
     cell.textLabel.text = array[indexPath.row] 
     cell.tag = indexPath.row 
     cell.targetForAction("getAction:", withSender: self) 
     return cell 
    } 

    func getAction(sender:UITableViewCell)->Void { 
     if(sender.tag == 0) { 
      println("it worked") 
     } 
    } 

我试着去适应从另一篇文章一个解决方案,但我这样做是肯定不对的。谢谢你在前进

回答

17

实施UITableViewDelegate和使用didSelectRowAtIndexPath

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) 

可以使用indexPath从您的收藏获得该项目,并执行行动

+1

谢谢,这是完美的! – soling 2014-10-30 12:27:12

+1

不要忘记实现'UITableViewDelegate'协议来获得'didSelectRowAtIndexPath'方法 – LynAs 2017-01-12 10:31:18

4

在斯威夫特4,相信该方法已经改变曾经如此轻微:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    // your code 
} 
相关问题