gpt4 book ai didi

ios - 自定义 UITableViewCell 按钮.backgroundColor 会自动更改

转载 作者:行者123 更新时间:2023-11-30 10:57:43 27 4
gpt4 key购买 nike

我有一个链接到TableViewCell.swift的自定义tablevVewCell,该单元格有一个按钮,当touchUpInside时,该按钮将按钮颜色更改为绿色,但是当创建新单元格(出列可重用属性)时,新单元格按钮也发生了更改(绿色) color 我也尝试使用 if-else 处理这个问题,但没有帮助。感谢所有帮助(我也在这里处理多个部分)。基本上我的问题是如何知道 TableViewCell 类中的按钮被点击并在 MainVC 中分配一个值?

主VC:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
cell.layer.cornerRadius = 20
cell.isUserInteractionEnabled = true

if objArray.count > 0 {
cell.courseCode.text = objArray[indexPath.section].code
cell.courseName.text = objArray[indexPath.section].name
cell.slot.text = objArray[indexPath.section].slot
cell.year.text = objArray[indexPath.section].year
cell.button.tag = indexPath.section
}

return cell
}

表格 View 单元格:

class TableViewCell: UITableViewCell {

@IBOutlet weak var courseName: UILabel!
@IBOutlet weak var courseCode: UILabel!
@IBOutlet weak var slot: UILabel!
@IBOutlet weak var year: UILabel!
@IBOutlet weak var downloadButton: UIButton!
@IBOutlet weak var button: UIButton!

var buttonIsSelected:Bool = false

override func awakeFromNib() {
super.awakeFromNib()
}

override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}

@IBAction func button(_ sender: Any) {
print(button.tag)
buttonIsSelected = true
button.backgroundColor = .green
}

}

最佳答案

来自 objArray 的对象应该有一些属性

var isSelected: Bool

然后,当用户按下按钮时,您应该更改按钮的此属性(例如使用委托(delegate)模式)。

您要做的最后一件事是根据项目的 isSelected 属性在数据源方法 cellForRowAt 中设置按钮的背景颜色

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
let item = objArray[indexPath.row]
cell.button.backgroundColor = item.isSelected ? .green : .white //default
...
}

注意:不要使用 indexPath.section,而是使用 indexPath.row

<小时/>

或者,如果您的自定义模型中不需要此 isSelected 属性,您可以将 objArray 设为字典。

关于ios - 自定义 UITableViewCell 按钮.backgroundColor 会自动更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53757868/

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