【问题标题】:swift-Tableview cell UIButton background colorswift-Tableview 单元格 UIButton 背景颜色
【发布时间】:2018-06-29 01:08:33
【问题描述】:

正在开发具有 tableview 的应用程序。在每个单元格中都有两个按钮(通过/失败)。如果用户点击“ok”,通过背景变为绿色,点击“!”失败,背景变为红色。我遇到的问题是,如果连续点击一个按钮(比如说失败按钮)。滚动到另一行(比如向下 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 任何帮助是极大的赞赏 谢谢。 抱歉,如果重新发布。只是被难住了。

【问题讨论】:

  • 您应该检查按钮是否已在 cellForRowAt 中被选中,然后相应地更改背景颜色。

标签: ios swift uibutton tableview


【解决方案1】:

首先,如果按钮已被选中,您必须保留一个参考。其次,最好在cellForRowAt函数上设置按钮的背景色。

为了保持选中按钮的引用可以通过多种方式实现。通常我使用一个对象数组,它在对象上有一个 bool 属性。

在您的情况下,我认为最简单的方法是这样的,因为您已经有一个用于单元格标题的字符串数组。您可以创建一个 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() }

不要忘记为表格视图创建一个出口。

【讨论】:

    【解决方案2】:

    您的应用似乎无法知道应该返回绿色,因为您只实现了一个将其更改为警报/红色的功能,但您没有检查其他任何内容,因此当您完成您的操作时if 语句,那么所有单元格都会改变,因为它们不知道不同。

    希望对你有帮助

    【讨论】:

      【解决方案3】:

      您可以通过将数组更改为字典并将值设置为真/假来跟踪按钮状态。

      例如var myArray = ["my": false, "hello": false]

      然后在 cellForRowAt cellForRowAt 中根据键的值设置状态,在 func errorBtn(_ sender: UIButton) 中只需切换选定的按钮值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-21
        • 1970-01-01
        • 2022-12-12
        • 2015-11-29
        • 1970-01-01
        • 2020-05-26
        • 2011-09-29
        • 2014-10-08
        相关资源
        最近更新 更多