2016-12-14 59 views
2

我有一個名爲Post的TableView和標籤。我有一個手勢點擊功能,當用戶點擊該標籤時,點擊的TableView標籤會改變顏色。這個問題是與tableView回收,如果我去了tableView,然後其他單元格也突出顯示,沒有點擊。我該如何解決這個問題,只有被點擊的單元格被突出顯示?這是我的代碼IOS Swift如何突出顯示使用TableView回收的單元格

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "UserProfileTVC", for: indexPath) as! UserProfileTVC 

     cell.post.text = Posts[indexPath.row] 
     let post_tap = UITapGestureRecognizer(target: self, action: #selector(UserProfileC.post_tapped(sender:))) 
     cell.post.addGestureRecognizer(post_tap) 
     return cell 
    } 


    func post_tapped(sender:UITapGestureRecognizer) { 

     let point = CGPoint(x: 0, y: 0) 

     let position: CGPoint = sender.view!.convert(point, to: self.TableSource) 
     if self.TableSource.indexPathForRow(at: position) != nil { 
      sender.view?.backgroundColor = UIColor.blue 

     } 
    } 

同樣的代碼工作,並強調了正確的TableCell標註問題是向下滾動的tableView其他tableCells標籤也沒有時,被點擊得到強調。

我已經更新了下面給出的示例代碼,但它仍然給了相同的結果

if let existingRecognizerView = cell.viewWithTag(101) as UIView? { 

     existingRecognizerView.backgroundColor = UIColor.white 


    } else { 

let post_tap = UITapGestureRecognizer(target: self, action: #selector(UserProfileC.post_tapped(sender:))) 
     post_tap.view?.tag = 101 

    cell.post.addGestureRecognizer(post_tap) 

    } 

回答

1

在你cellForRowAtIndexPath功能你離隊已經有一個UITapGestureRecognizer上,並用藍色背景的單元格。您需要在其視圖中添加標籤,以便在出列和移除背景顏色時可以訪問它。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "UserProfileTVC", for: indexPath) as! UserProfileTVC 

    cell.post.text = Posts[indexPath.row] 

    // Check if we already have a GestureRecognizer view 
    if let existingRecognizerView = cell.post.viewWithTag(101) { 
     existingRecognizerView.backgroundColor = UIColor.white 
    } else { 
     let post_tap = UITapGestureRecognizer(target: self, action: #selector(UserProfileC.post_tapped(sender:))) 
     cell.post.addGestureRecognizer(post_tap) 
     post_tap.view.tag = 101 
    } 

    return cell 
} 


func post_tapped(sender:UITapGestureRecognizer) { 

    let point = CGPoint(x: 0, y: 0) 

    let position: CGPoint = sender.view!.convert(point, to: self.TableSource) 
    if self.TableSource.indexPathForRow(at: position) != nil { 
     sender.view?.backgroundColor = UIColor.blue 

    } 
} 

*注意:從移動設備編碼...未測試語法或功能錯誤。

+0

好的,謝謝你的方向,我把你的代碼,它絕對感覺它是在正確的方向,雖然我仍然得到相同的結果。我會發布我剛剛實施的內容。我改變了可選的從?到UIView?像之前我得到一個向下鑄造錯誤和相似性這個post_tap.view?.tag,但其他一切都是一樣的。 –

+0

好吧,我只是做了一個改變。沒有意識到你在你的手機中有一個子視圖。添加'如果讓existingRecognizerView = cell.post.viewWithTag(101)'。你可以在'existingRecognizerView.backgroundColor = UIColor.white'這一行刪除一個斷點,看它是否被調用? – toddg

+0

完美的工作非常感謝,是的,我放棄了它的斷點,它被稱爲。 –

相關問題