2014-10-30 25 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 
} 
相關問題