【问题标题】:In swift, how to manage two buttons in same custom tableview cell?快速,如何管理同一个自定义表格视图单元格中的两个按钮?
【发布时间】:2019-11-12 23:53:30
【问题描述】:

我正在尝试管理同一个自定义表格视图单元格中的两个按钮。 添加了两个名为 Yes 和 No 的按钮。如果选择 Yes 按钮,No 按钮将处于非活动状态,而 Yes 按钮将变为活动状态。

这是我需要的图片

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell") as! TableViewCell
    cell.yesButton.tag = 101
    cell.noButton.tag = 102
    cell.yesButton.addTarget(self, action: #selector(buttonClicked(sender:)), for: UIControl.Event.touchUpInside)
    cell.noButton.addTarget(self, action: #selector(buttonClicked(sender:)), for: UIControl.Event.touchUpInside)
    return cell
}

 @objc func buttonClicked(sender: AnyObject) {
    let buttonPosition = (sender as AnyObject).convert(CGPoint.zero, to: tableList)
    let indexPath = tableList.indexPathForRow(at: buttonPosition)
    if sender.tag == 101 {
        if indexPath != nil {
            print("Cell indexpath = \(String(describing: indexPath?.row))")
        }
    }

    if sender.tag == 102 {
        if indexPath != nil {
            print("Cell indexpath = \(String(describing: indexPath?.row))")
        }
    }
}

【问题讨论】:

  • 那么问题是什么?
  • 严格来说,您不使用 custom 表格视图单元格。您正在使用带有自定义对象的标准表格视图单元格。不要那样做。使用 real custom 样式和包含 IBOutlets 的自定义类设计一个表格视图单元格。在此单元格中,您可以实现自定义逻辑来控制按钮。处理标签来识别 UI 元素已经过时了很长时间。
  • 您可以在标签中使用枚举,例如 enum SenderTags: Int { case foo = 101, case foo2 = 102 }

标签: ios swift uitableview uibutton


【解决方案1】:

为每个tableViewCell创建一个模型来维护yesButton和noButton的状态,即

class Model {
    var isYesSelected = false
    var isNoSelected = false
}

使用Outlets 的yesButton 和noButton 创建一个自定义UITableViewCell。

为buttons 创建一个@IBAction,并根据button 被点击来处理他们的UI。

此外,使用buttonTapHandler 来识别button 被窃听的row。每次点击button 时都会调用它。我们将在tableView(_:cellForRowAt:) 中创建TableViewCell 的实例时进行设置。

class TableViewCell: UITableViewCell {
    @IBOutlet weak var yesButton: UIButton!
    @IBOutlet weak var noButton: UIButton!

    var buttonTapHandler: (()->())?
    var model: Model?

    override func prepareForReuse() {
        super.prepareForReuse()
        yesButton.backgroundColor = .gray
        noButton.backgroundColor = .gray
    }

    func configure(with model: Model) {
        self.model = model
        self.updateUI()
    }

    @IBAction func onTapButton(_ sender: UIButton) {
        model?.isYesSelected = (sender == yesButton)
        model?.isNoSelected = !(sender == yesButton)
        self.updateUI()
    }

    func updateUI() {
        yesButton.backgroundColor = (model?.isYesSelected ?? false) ? .green : .gray
        noButton.backgroundColor = (model?.isNoSelected ?? false) ? .green : .gray
    }
}

UITableViewDataSource'stableView(_:cellForRowAt:) 方法如下,

let numberOfCells = 10
var models = [Model]()

override func viewDidLoad() {
    super.viewDidLoad()
    (0..<numberOfCells).forEach { _ in
        self.models.append(Model())
    }
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return numberOfCells
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! TableViewCell
    cell.configure(with: models[indexPath.row])
    cell.buttonTapHandler = {
        print(indexPath.row)
    }
    return cell
}

要获得totalPoints,请将models 与isYesSelected = true 一起计算,即

let totalPoints = models.reduce(0) { (result, model) -> Int in
    if model.isYesSelected {
        return result + 1
    }
    return 0
}
print(totalPoints)

【讨论】:

  • 这应该有一个模型表单元格出列
  • @Sh_Khan 没听懂你。请解释一下。
  • 此外,没有任何指定,就像 OP 想要在任何地方保存该状态。
  • @PGDev 当我们滚动表格时,按钮颜色会发生变化。
  • 那么你必须在模型中维护它。你应该在问题本身中澄清这一点。
【解决方案2】:

使用您的标签获取该按钮,如下所示,之后,您可以根据需要更改值。

var tmpButton = self.view.viewWithTag(tmpTag) as? UIButton

【讨论】:

    【解决方案3】:

    简单的 3 步过程...!!

    1. 定义模型类
    2. 准备 tableView 单元格并处理操作
    3. 在视图控制器中设置tableView

    让我们开始实施吧:

    1) 定义模型类

    在 UI 中,我们有类似问题及其答案(是/否)之类的信息。所以分别设计模型。

    //MARK:- Class Declaration -
    class Question {
          let questionText: String
          var answerState: Bool?
    
          init(question: String) {
               self.questionText = question
          }
    }
    

    2。准备 tableView 单元并处理操作

    使用问题标签、是按钮和否按钮创建自定义tableView单元格。将该视图与受人尊敬的@IBOutlets 和@IBActions 联系起来。

    import UIKit
    
    class TableViewCell: UITableViewCell {
          @IBOutlet weak var questionLabel: UILabel!
          @IBOutlet weak var yesButton: UIButton!
          @IBOutlet weak var noButton: UIButton!
    
          var question: Question?
          var toggle: Bool? {
              didSet {
                     question?.answerState = toggle
                     //Do buttons operations like...
                     if let isToggle = toggle {
                        yesButton.backgroundColor = isToggle ? .green : .gray
                        noButton.backgroundColor = isToggle ? .gray : .green
                     } else {
                        yesButton.backgroundColor =  .gray
                        noButton.backgroundColor = .gray
                     }
              }
          }
    
          func prepareView(forQuestion question: Question) {
               self.question = question
               questionLabel.text = question.questionText
               toggle = question.answerState
          }
    
          //Yes Button - IBAction Method
          @IBAction func yesButtonTapped(_ sender: UIButton) {
                toggle = true
          }
    
          //No Button - IBAction Method
          @IBAction func noButtonTapped(_ sender: UIButton) {
                toggle = false
          }
    }
    

    3.在视图控制器中设置 tableView

    class ViewController: UIViewController {
    
        //Prepare questions model array to design our tableView data source
        let arrQuestions: [Question] = [Question(question: "Do you speak English?"), Question(question: "Do you live in Chicago?")]
    }
    
    //MARK:- UITableView Data Source & Delegate Methods -
    extension ViewController: UITableViewDataSource, UITableViewDelegate {
    
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return arrQuestions.count
        }
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            guard let tableViewCell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell") as? TableViewCell else {
                return UITableViewCell()
            }
            tableViewCell.prepareView(forQuestion: arrQuestions[indexPath.row])
            return tableViewCell
        }
    
        func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            return 80.0
        }
    }
    

    【讨论】:

      【解决方案4】:
      • 创建基本的tableView并配置dataSource函数

      • 使用两个按钮创建 tableView 单元格

      • 使用按钮插座和操作创建单元格类

      • 此代码的结果

      享受吧!

      【讨论】:

        猜你喜欢
        • 2014-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-04
        相关资源
        最近更新 更多