2017-04-26 29 views
0

我有一個UITableViewCell,我想顯示爲UIViewController時提供選擇。 vc.tableView.selectRow:atIndexPath理論上不錯,但它繞過了單元上willSelectdidSelect的呼叫。設置UITableViewCell之前提出

單元格有一個公開的UIImageView,它可以切換,這是我試圖在初始加載時顯示的內容。

任何幫助在這裏將不勝感激。謝謝!

回答

0

我給你換背景你的細胞如何顏色的例子並選擇最初的一,這樣你就可以遵循,把你需要的代碼:

在你UIViewController子類,實現這些方法,所以你可以把你的邏輯選擇和取消選擇狀態:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    let selectedCell = tableView.cellForRow(at: indexPath)! 
    selectedCell.backgroundColor = UIColor.purple 
} 

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { 
    let deselectedCell = tableView.cellForRow(at: indexPath)! 
    deselectedCell.backgroundColor = UIColor.clear 
} 

在您的自定義UITableViewCell子類必須重寫isSelected財產,這是爲了避免方法tableView.selectRow:atIndexPath繞過didSelect關鍵:

class CustomTableViewCell: UITableViewCell { 

    override var isSelected: Bool {   
     didSet { 
      print(isSelected.description) 
      self.selectionStyle = .none 
      if isSelected{ 
       self.backgroundColor = UIColor.purple 
      } else { 
       self.backgroundColor = UIColor.clear 
      } 
     } 
    } 

} 

最後,回到你的UIViewController子類,你可以調用selectRow:atIndexPathviewDidLoad方法,例如:

override func viewDidLoad(){ 
    super.viewDidLoad() 
    tableView.selectRow(at: IndexPath(row: 0, section: 0) , animated: true, scrollPosition: UITableViewScrollPosition.none) 
} 
+0

感謝您的回答,亞歷山大。然而問題是''tableView.selectRow(at:IndexPath(row:0,section:0),animated:true,scrollPosition:UITableViewScrollPosition.none)''跳過'willSelect'和'didSelect'按照文檔 –

+0

@ZackShapiro是的,它跳過。這就是爲什麼我創建了一個自定義的'UITableViewCell'和overrided'isSelected'屬性,你可以把它放在你的邏輯中,所以當你調用'tableView.selectRow(at :)' –

+0

啊,我錯過了那部分不會被繞過。我的錯。我會試一試。謝謝! –

相關問題