【问题标题】:Accessing UIButton via accessibility identifier in cell通过单元格中的可访问性标识符访问 UIButton
【发布时间】:2016-12-21 15:15:38
【问题描述】:

我如何访问Cell 中存在的Button 及其可访问性

Setting button's accessibility identifier in some method

现在我需要从上面第 1 步中设置的可访问性标识符访问单元格内存在的那个按钮

我可以通过标签设置标签和访问项目,但找不到标识符方法

【问题讨论】:

  • 上下文是什么?为什么你需要这样做?也许我们可以推荐其他替代品。

标签: ios xcode uitableview uibutton


【解决方案1】:

我更喜欢使用委托

class protocol ButtonCellDelegate: class {
    func didPressButtonInCellAt(_ indexPath: IndexPath)

}

你应该在你的单元类代码中添加这样的东西

class YourCell: UITableViewCell {
    weak var delegate: ButtonCellDelegate?
    var indexPath: IndexPath?
    ...
   @IBAction func buttonPressed() {
        if let indexPath = indexPath, let delegate = delegate {
            delegate.didPressButtonInCellAt(indexPath)
        }
    }
}

而实现本身是:

class YourTableViewController: UITableViewController, ButtonCellDelegate {

     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        ...
        cell.delegate = self
        cell.indexPath = indexPath
        ...

    }

    func didPressButtonInCellAt(_ indexPath: IndexPath) {
        //Things you want to do, if a button is pressed
    }

}

但是如果你仍然想使用标签,你可以使用sender传递它们

class YourTableViewController: UITableViewController {

     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        ...
        cell.button.tag = indexPath.row
        ...

    }

    @IBAction func buttonPressed(sender: UIButton) {
         let row = sender.tag
         //Things you want to do, if a button is pressed
    }
}

使用委托是处理此类问题的更稳健的方式,因为它可以轻松处理多节表视图并且更易于维护。

如果您的按钮是通过编程方式创建的,您可以添加如下操作:

    //YourCell
override func awakeFromNib() {
         super.awakeFromNib()
         let button = UIButton() //replace with your initialization
         button.addTarget(self, action: #selector(pressed(sender:)), for: .touchUpInside)
}

func pressed(sender: UIButton!) {
        if let indexPath = indexPath, let delegate = delegate {
            delegate.didPressButtonInCellAt(indexPath)
        }
    }

如果你还想使用标签,你只需要在viewDidLoad中使用addTarget就可以了

【讨论】:

  • 感谢您的回答。这似乎可以理解,但我忘了提一件事。按钮正在以编程方式添加。您在这种情况下的建议。
猜你喜欢
  • 2017-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-27
  • 1970-01-01
  • 2011-05-06
  • 1970-01-01
相关资源
最近更新 更多