ios - tableview 单元格中的 UIButton 更改文本

标签 ios swift uitableview uibutton

我知道 SO 之前已经回答过这些类型的问题,但我的问题略有不同,所以请阅读。

我在 tableview 单元格中使用了一个按钮。单击按钮时,我将显示一个带有操作列表的 AlertViewController。在选择操作时,我的按钮文本和我的自定义模型类属性发生了变化。

按钮文本在按钮点击时发生变化。但我的问题是单元格不存储按钮状态。如果我更改第一个单元格的按钮,然后单击第二个单元格按钮,所有其他按钮将恢复为默认文本。

please see this video

这是我的代码

设置单元格数据

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("dbColumns", forIndexPath: indexPath) as! CustomColumnTableViewCell

        let column = columns[indexPath.row]
        cell.dbColumnName.text = column.name
        cell.dbColumnOrder.titleLabel?.text = column.order
        cell.dbColumnOrder.tag = indexPath.row

        print(columns)
        cell.dbColumnOrder.addTarget(self, action: #selector(ViewController.showAlert(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        return cell
    }

按钮点击 Action

//MARK:Show Alert
    func showAlert(sender:UIButton){
        let alert = UIAlertController(title: "Column Order", message: "Please select column order", preferredStyle: .ActionSheet)
        let index = sender.tag
        let indexPath = NSIndexPath(forRow: index, inSection: 0)

        alert.addAction(UIAlertAction(title: "None", style: .Default, handler: { (action) in
            //execute some code when this option is selected
            self.columns[index].order = "None"
            self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
        }))

        alert.addAction(UIAlertAction(title: "Assending", style: .Default, handler: { (action) in
            //execute some code when this option is selected
            self.columns[index].order = "Assending"
            self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
        }))

        alert.addAction(UIAlertAction(title: "Desending", style: .Default, handler: { (action) in
            //execute some code when this option is selected
            self.columns[index].order = "Desending"
            self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
        }))

        self.presentViewController(alert, animated: true, completion: nil)
    }

请帮帮我。

最佳答案

cellForRowAtIndexPath 方法中这样设置按钮文本 先去掉这个

cell.dbColumnOrder.titleLabel?.text = column.order

替换这个

cell.dbColumnOrder.setTitle("\(column.order)", for: .normal)

您还需要增加 cell.dbColumnOrder 宽度。

希望它有用

关于ios - tableview 单元格中的 UIButton 更改文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41012800/

相关文章:

swift - RealmSwift + 多谓词

ios - Cell.imageView.image 更改后不会自动加载

ios - 将 EC_KEY OpenSSL 中的公钥和私钥导出到 SecKeyRef

ios - UITableViewCell 单元重用和 UILabel 自动布局动态调整大小

ios - Objective-C:如何获取 UIScrollView 的缩放内容

ios - 在详细 Controller 中打开通知

ios - 一旦下一个以模态方式出现,就关闭或删除以前以模态方式呈现的 View Controller

ios - 哪个事件用于检测 UITextfield 处于 null 状态

ios - 从另一个 View Controller 将对象添加到数组

ios - 单击 UITableViewCell 时更新标签