![](/img/trans.png)
[英]UITableviewcell with UIbutton , changes tableview cell background color
[英]swift-Tableview cell UIButton background color
使用具有表格视图的应用程序。 在每个单元格中都有两个按钮(通过/失败)。 如果用户点击“确定”,则通过的背景将变为绿色,而“!” 失败,背景变为红色。 我遇到的问题是,如果连续点击了一个按钮(假设失败按钮)。 滚动淹没到另一行(如向下5行)。 故障按钮的背景色也已更改(红色)。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: CellTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "cell") as! CellTableViewCell
if cell == nil
{
cell = CellTableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.text = myArray[indexPath.row]
cell.fail.tag = indexPath.row
cell.fail.addTarget(self, action: #selector(ViewController.errorBtn(_:)), for: .touchUpInside)
}
else
{
cell.textLabel?.text = myArray[indexPath.row]
cell.fail.tag = indexPath.row
cell.fail.addTarget(self, action: #selector(ViewController.errorBtn(_:)), for: .touchUpInside)
}
return cell
}
这是带有问题的代码的应用程序快速模型的链接。 https://github.com/morenoa/iOS3/tree/master/Table%20Cell非常感谢您的帮助。 抱歉,如果重新发布。 只是难住了。
您的应用似乎没有办法知道应返回绿色,因为您仅实现了将其更改为警报/红色的功能,但您没有检查其他任何内容,因此当您在if语句中完成操作时,然后所有的细胞都会改变,因为他们没有不同的认识。
我希望这有帮助
您可以通过将数组更改为字典并将值设置为true / false来跟踪按钮状态。
例如var myArray = ["my": false, "hello": false]
然后根据键的值在cellForRowAt cellForRowAt
设置状态,在func errorBtn(_ sender: UIButton)
只需切换所选按钮的值即可。
首先,您必须保留一个参考,以确保该按钮已被选中。 其次,最好在cellForRowAt
函数上设置按钮的背景色。
为了保持对所选按钮的参考,可以以各种方式实现。 通常我使用一个对象数组,该对象在对象上具有bool属性。
就您而言,我认为最简单的方法是这样的,因为您已经有一个用于单元格标题的字符串数组。 您可以创建布尔数组来保持按钮状态。 如:
var myArraySelected:[Bool] = [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]
然后在cellForRowAt
放置以下代码以设置按钮的背景色
if (myArraySelected[indexPath.row]){ cell.fail.backgroundColor = UIColor.red }else{ cell.fail.backgroundColor = UIColor(red: 214.0/255.0, green: 214.0/255.0, blue: 214.0/255.0, alpha: 1.0) }
最后,将errorBtn操作更改为:
@IBAction func errorBtn(_ sender: UIButton) { myArraySelected[(sender as AnyObject).tag] = true self.tableView.reloadData() }
不要忘记为表格视图创建出口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.