gpt4 book ai didi

swift - 当我向下滚动并快速返回时,Tableview 单元格设置保持更改

转载 作者:行者123 更新时间:2023-11-28 08:01:06 25 4
gpt4 key购买 nike

我正在尝试制作像这张图片 (1) 这样的表格 View 。当表格 View 单元格的文本出现“取消计划”或“休息日”时,按钮“>”将变为灰色,单元格无法点击。

我的代码可以正常工作,但是当我向下滚动并返回时,设置会乱七八糟。设置会像图像(2)和(3)一样随机变化。为什么?

图片(1):https://www.dropbox.com/s/0k6ldrfx5nzyt9e/1.jpg?dl=0

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "rosterId", for: indexPath) as! RosterCell
...
if jobCancel[indexPath.section] == 0{
cell.separator.backgroundColor = UIColor.darkGray
cell.jobDetail.textColor = UIColor.gray
cell.button.isEnabled = false
cell.button.alpha = 0.3;
}
if cell.jobDetail.text == "Cancelled Schedule"{
cell.separator.backgroundColor = UIColor.red
cell.button.isEnabled = false
cell.button.alpha = 0.3;
cell.isUserInteractionEnabled = false
}
if cell.jobDetail.text == "Off Day"{
cell.separator.backgroundColor = UIColor.darkGray
cell.button.isEnabled = false
cell.button.alpha = 0.3;
cell.isUserInteractionEnabled = false
}

}

类似于图片(2) 或图片(3)

图片(2):https://www.dropbox.com/s/jmile0vxpcqgt92/2.jpg?dl=0

图片(3):https://www.dropbox.com/s/94ef4hb996afmm6/3.jpg?dl=0

最佳答案

这样做的原因是细胞复用。

这意味着可以重复使用以某种方式设置样式的单元格来显示不同的数据。您必须确保每次重复使用单元格时设置样式的各个方面以避免交叉。

如果您制作一个 configureCell 方法来处理它,可能更容易跟踪样式,这样您就不会忘记设置一个值,您甚至可以设置一些默认值。

func configureCell(cell:RosterCell,
textColour:UIColor,
seperatorColour:UIColor,
buttonEnabled:Bool,
buttonAlpha:CGFloat,
interactionEnabled:Bool = false) {

cell.separator.backgroundColor = seperatorColour
cell.jobDetail.textColor = textColour
cell.button.isEnabled = buttonEnabled
cell.button.alpha = buttonAlpha
cell.isUserInteractionEnabled = interactionEnabled

}

那么您的cellForRowAt 方法将如下所示

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "rosterId", for: indexPath) as! RosterCell
...
if jobCancel[indexPath.section] == 0{
configureCell(cell: cell,
textColour: UIColor.gray,
seperatorColour: UIColor.darkGray,
buttonEnabled: false,
buttonAlpha: 0.3,
interactionEnabled: true)
}
if cell.jobDetail.text == "Cancelled Schedule"{
configureCell(cell: cell,
textColour: UIColor.gray,
seperatorColour: UIColor.red,
buttonEnabled: false,
buttonAlpha: 0.3)
}
if cell.jobDetail.text == "Off Day"{
configureCell(cell: cell,
textColour: UIColor.gray,
seperatorColour: UIColor.darkGray,
buttonEnabled: false,
buttonAlpha: 0.3)
}

}

如您所见,我已将 interactionEnabled 参数默认设置为 false,因此我不需要为最后两个 if 语句设置它。

关于swift - 当我向下滚动并快速返回时,Tableview 单元格设置保持更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46685408/

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