gpt4 book ai didi

ios - 由于单元重复使用而导致按钮重叠

转载 作者:行者123 更新时间:2023-11-30 12:22:54 24 4
gpt4 key购买 nike

我在使用 UITableView 中的出列可重用单元格函数时遇到一些问题。表格 View 有几个单元格,每个单元格都包含一个按钮。

当我滚动时,单元格被重新创建,新按钮开始重叠旧按钮(直到我在同一个单元格中有一堆相同的按钮)。我听说您应该使用 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"
])

最佳答案

您看到多个按钮出现的原因是因为每次需要新的表格单元格时都会调用 cellForRowAtIndexPath: 方法。由于您可能在该方法主体中创建按钮,因此每次重用单元格时都会重新创建按钮,并且您会看到它们像这样堆叠在顶部。将 dequeueReusableCell: 与自定义元素一起使用的正确方法是创建 UITableViewCell 的子类并将其设置为 Storyboard 中的表格单元格的类。然后,当您调用 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
}
}

关于ios - 由于单元重复使用而导致按钮重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44579156/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com