我將數據傳遞給自定義UITableViewCell並基於該數據顯示或隱藏動態添加的子視圖。我正在重用故事板中創建的單元格。一切都按預期工作,直到某些單元格被重用爲止,例如在滾動它時將「隨機」隱藏或顯示動態添加的子視圖。將數據傳遞給自定義UITableViewCell並添加子視圖
我需要什麼
我需要的方式通過方法(使用setData)來設置一個單元的數據,增加一個動態創建的子視圖,同時允許細胞而不產生毛刺被重用它的外觀,特別是增加的子視圖以及細胞狀態。
問題
我不知道我應該創建子視圖,因此它不具有當電池被重複使用,以重新創建,所以它不會錯誤時,我想隱藏或在setData方法中顯示它。同時創建新的子視圖時可以訪問IBOutlet storyboardLabel。
CustomTableViewCell
class CustomTableViewCell : UITableViewCell {
var data: DataItem?
var customSubview: UIView?
@IBOutlet weak var storyboardLabel: UILabel!
//setting the data of a cell and adding the subview
func setData(DataItem data) {
// adding the view
let customSubview = UIView.init(...)
customSubview.bounds = storyboardLabel.bounds
customSubview.hidden = data.showSubview
self.contentView.addSubview(customSubview)
}
}
添加細胞
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("storyboardTableCell") as! CustomTableViewCell
cell.setData(self.data[indexPath.section][indexPath.row] as! DataItem)
return cell
}
你看過'prepareForReuse()'了嗎? – Eendje
我確實做了,但是我正在尋找一個解決方案,而不重新創建子視圖,如果有的話。因爲在我看來,重新使用它時似乎沒有必要再使用它。 –
你可以做的是懶洋洋地創建子視圖並在'prepareForReuse'中檢查它是否存在並隱藏它。我認爲SwiftArchitect的解釋應該足夠了,但如果你仍然需要幫助,我可以告訴你如何。 – Eendje