2014-10-30 10 views
8

में किसी सेल पर क्लिक करता है तो मैं एक क्रिया को ट्रिगर करता हूं, मैं स्विफ्ट का उपयोग करके एक ऐप बना रहा हूं। मेरे पास 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

+1

'didSelectRowAtIndexPath' विधि प्राप्त करने के लिए' UITableViewDelegate 'प्रोटोकॉल को लागू करना न भूलें – LynAs

4

स्विफ्ट 4 में, मेरा मानना ​​है कि विधि बदल गया है कभी इतना छोटा:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    // your code 
} 
संबंधित मुद्दे