2017-06-16 77 views
0

我在我的UITableView中出現了可重複使用的細胞功能出現了一些問題。 tableview有幾個單元格,每個單元格都包含一個按鈕。由於細胞再利用導致的重疊按鈕

當我滾動時,單元格被重新創建,並且新按鈕開始重疊舊按鈕(直到我在同一個單元格中有一堆相同的按鈕)。我聽說你應該使用removeFromSuperview函數來解決這個問題,但我不確定如何去做。

這裏是我的應用程序的圖片:

image

這裏是cellForRowAtIndexPath(其中問題發生)

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


    let nameLabel: UILabel = { 
     let label = UILabel() 
     label.text = "Sample Item" 
     label.translatesAutoresizingMaskIntoConstraints = false 
     return label 
    }() 

    let actionButton = YSSegmentedControl(
     frame: CGRect.zero, 
     titles: [ 
      "No", 
      "Yes" 
     ]) 
+0

您還沒有發佈'cellForRowAtIndexPath'的整個函數。你需要發佈更多的功能。特別是,您將標籤和按鈕/分段控件添加到單元格的位。我懷疑你每次出隊時都會添加這些項目,而不會刪除它們。你的形象是否真的說明了這個問題?我看不到圖像中的任何重疊按鈕。 –

+0

不建議在'cellForRowAt indexPath.'中創建或刪除視圖。 – Maddy

回答

0

你看到多個按鈕的出現是因爲原因每次需要新的表格單元格時,都會調用cellForRowAtIndexPath:方法。由於您可能在該方法體中創建按鈕,因此每次單元格被重用時都會重新創建該按鈕,並且您會看到它們堆疊在頂部。使用dequeueReusableCell的正確方法是:使用自定義元素創建UITableViewCell的子類並將其設置爲故事板中表格單元格的類。然後當你調用dequeueReusableCell時:你會得到一個你的子類的副本,它將包含你所有的自定義代碼。你需要做一個類型轉換得到任何的是自定義代碼這樣的訪問:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ 
    if let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as? MyCustomCellClass { 
    cell.nameLabel.text = "Sample item" 
    } 

    // This return path should never get hit and is here only as a typecast failure fallback 
    return tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath); 
} 

您的自定義單元格的子類會再看看這樣的事情:

class MyCustomCellClass: UITableViewCell { 
    @IBOutlet var nameLabel: UILabel! 
    @IBOutlet var actionButton: UIButton! 

    @IBAction func actionButtonPressed(_ sender: UIButton) { 
    //Do something when this action button is pressed 
    } 
} 
+0

換句話說,*永遠不會*添加或刪除'cellForRowAt'中的子視圖。相反,將它們添加到別處(*咳嗽*故事板*咳嗽*),並在'cellForRowAt'中更改它們的*屬性*。 – NRitH

+0

我會,但我不使用故事板。我嘗試過使用自定義單元類,但它顯得更加困難。 –

+0

@NicholasTiwari如果我的記憶正確地爲我服務(這已經有一段時間了),但是如果你不想使用完整的故事板,你應該只能使用普通的nib文件。否則,自定義單元類是要走的路。如果您正在爲此苦苦掙扎,請發佈問題以便我們提供幫助。 – JiuJitsuCoder

0

您可以添加新標籤/按鈕cellForRowAtIndexPath,但在創建並添加新標籤之前,您需要確保沒有現有的標籤/按鈕。一種方法是將標籤設置爲標籤/按鈕,並且在生成新標籤/按鈕之前,檢查包含標籤的視圖是否已經在單元格中。

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

    if let label = cell.viewWithTag(111) as? UILabel 
    { 
     label.text = "Second Labels" 
    } 
    else{ 
     let label = UILabel() 
     label.tag = 111 
     label.text = "First Labels" 
     cell.addSubview(label) 
     label.translatesAutoresizingMaskIntoConstraints = false 
     label.frame = CGRect(x:0, y:10, width: 100, height:30) 
    } 

    return cell 
}