通过单元格中的可访问性标识符访问UIButton

时间:2016-12-21 15:15:38

标签: ios xcode uitableview uibutton

如何访问Button中存在的Cell及其辅助功能

Setting button's accessibility identifier in some method

现在我需要从上面步骤1中设置的辅助功能标识符访问单元格内的按钮

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

1 个答案:

答案 0 :(得分: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
    }
}

使用delegeates是处理此类问题的更强大的方法,因为它可以很容易地处理多节表视图并且更易于维护。

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

    //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)
        }
    }

如果您仍想使用代码,则只需在addTarget中使用viewDidLoad即可