2016-07-24 56 views
0

自定義單元類具有override func layoutSubviews(),其中每個單元格的detailTextLabel都被賦予標題「Jim」。單擊DidSelectRowAtIndexPath後,是否有方法永久更改單元格的細節文本(以阻止單元格不斷細化Jim),讓我們說「Bob」?如何修改DidSelectRowAtIndexPath中的自定義單元格

//This function is in the custom cell UserCell 
 

 
class CustomCell: UITableViewCell { 
 
override func layoutSubviews() { 
 
     super.layoutSubviews() 
 
     
 

 
     
 
      detailTextLabel?.text = "Jim" 
 
    } 
 

 
///........ 
 
} 
 

 

 
//In the viewController with the tableView outlet 
 
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 
 

 
//..... 
 

 

 
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
 
     let cell = tableView.dequeueReusableCellWithIdentifier(cellId, forIndexPath: indexPath) as! CustomCell 
 
     
 
     //...... 
 
     
 
     
 
     return cell 
 
    } 
 

 

 
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
 

 
/* Code I need to convert the detailTextLabel.text to equal "Bob" upon clicking on certain cell */ 
 

 
}

回答

0

很簡單,像這樣做:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 

detailTextLabel?.text = "Bob" 

} 
+0

謝謝你的回答,儘管我已經嘗試過了,它仍然是Jim,重寫func layoutSubviews在tableView重新載入時被調用,因此在我將它聲明爲我的didSelectRow中的Bob後將它放回到Jim。 ... – slimboy

0

本身不應該被用來保持狀態的任何數據,而只是將其顯示在單元格。在控制器上創建一個可變數組屬性以保存下層數據(字符串)。通過讀取此數組來設置新單元格的文本屬性,並在tableView:didSelectRowAtIndexPath:中將數組中"Bob"索引處的值更改爲"Jim"。每當tableView重新加載時,它現在將從dataSource中讀取更新後的值。

除了UITableViewDelegate協議還研究了UITableViewDataSource協議。默認情況下,UITableViewController類符合這兩種協議,並分配爲屬性的.tableView屬性(如果您反思其self.tableView.delegateself.tableView.datasource值,您將收到原始UITableViewController)。如果您手動創建了自己的從UIViewController繼承的tableview控制器類,那麼您將需要在tableView上分配這兩個屬性,以使其正常工作。

相關問題