2016-08-10 92 views
0

我有一個標籤,我想使用addGestureRecognizer。我把它放在cellForRowAtIndexPath,但是當我做print(label.text)時,它從另一個單元打印標籤。但是當我將它放入didSelectRowAtIndexPath時,它會打印出該單元的正確標籤。點擊表格視圖中的標籤?

解決此問題的最佳方法是什麼?

下面是代碼:

var variableToPass: String! 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
    { 
     let cell : MainCell! = tableView.dequeueReusableCellWithIdentifier("MainCell") as! MainCell 

     variableToPass = label1.text 

     cell.label1.userInteractionEnabled = true 
     let tapLabel = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapLabel(_:))) 
     cell.label1.addGestureRecognizer(tapLabel) 



     return cell as MainCell 
    } 

func tapCommentPost(sender:UITapGestureRecognizer) { 
    print(variableToPass) 
    } 
+2

您可以顯示的tableview執行'cellForRowAtIndexPath'代碼和動作代碼 –

+0

使用自定義的UITableViewCell類。 –

+0

@ Anbu.Karthik剛剛編輯過文章 – johnniexo88

回答

1

我想你忘記設置tap.tag = indexPath.row用於識別找到你標籤,其細胞,例如

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
    { 
     let cell : MainCell! = tableView.dequeueReusableCellWithIdentifier("MainCell") as! MainCell 

     variableToPass = label1.text 

     cell.label1.userInteractionEnabled = true 
     let tapLabel = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapLabel(_:))) 
     cell.label1.tag = indexPath.row 
     tapLabel.numberOfTapsRequired = 1 
     cell.label1.addGestureRecognizer(tapLabel) 



     return cell as MainCell 
    } 

func tapLabel(sender:UITapGestureRecognizer) { 

    let searchlbl:UILabel = (sender.view as! UILabel) 
    variableToPass = searchlbl.text! 
    print(variableToPass) 
    } 
+0

請問您可以根據我上面編輯的問題更改答案嗎? – johnniexo88

+0

@ johnniexo88 - ya sure –

+0

@ johnniexo88 - 查看更新後的答案 –

0

有與您當前密碼的幾個問題:(1)您將variableToPass設置爲cellForRowAtIndexPath:,因此假設label1.text是屬於該單元格的標籤,隨着表格加載,variableToPass將始終包含上次加載的單元格的標籤文本。 (2)cellForRowAtIndexPath:可以爲每個單元格調用多次(例如,在您滾動時),以便您可以將多個手勢識別器添加到單個單元格。

爲了解決問題#1,請完全刪除variableToPass變量,而是直接訪問手勢的標籤視圖。爲了解決問題#2,我建議將手勢識別器添加到您的自定義MainCell表視圖單元格中,但如果您不想這樣做,至少只添加一個手勢識別器(如果尚未存在)。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

    let cell = tableView.dequeueReusableCellWithIdentifier("MainCell") as! MainCell 

    if cell.label1.gestureRecognizers?.count == 0 { 
     cell.label1.userInteractionEnabled = true 

     let tapLabel = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapCommentPost(_:))) // I assume "tapLabel" was a typo in your original post 
     cell.label1.addGestureRecognizer(tapLabel) 
    } 

    return cell 
} 

func tapCommentPost(sender:UITapGestureRecognizer) { 
    print((sender.view as! UILabel).text) // <-- Most important change! 
} 
相關問題