ios - 从 UITableViewCell 的 accessoryView 中的自定义按钮获取索引路径

标签 ios swift uitableview uisearchcontroller

我有一个 UISearchController,它有一个单独的 UITableViewController 作为它的 searchResultsController

class SearchResultsViewController: UITableViewController {

    var fruits: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.tableFooterView = UIView(frame: .zero)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    }

    @objc func addFruit(_ sender: UIButton) {
        let point = tableView.convert(sender.bounds.origin, to: sender)
        let indexPath = tableView.indexPathForRow(at: point)
        print(indexPath?.row)
    }

    // MARK: - Table view data source
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return fruits.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = fruits[indexPath.row]
        cell.selectionStyle = .none

        let addButton = UIButton(type: .custom)
        addButton.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        addButton.setImage(UIImage(named: "add"), for: .normal)
        addButton.contentMode = .scaleAspectFit
        addButton.addTarget(self, action: #selector(addFruit(_:)), for: .touchUpInside)
        addButton.sizeToFit()
        cell.accessoryView =  addButton

        return cell
    }

}

我需要在显示搜索结果的单元格中显示自定义按钮。所以我添加了一个 UIButton 作为单元格的 accessoryView。它看起来和工作正常。

enter image description here

现在我需要在用户点击此按钮时获取单元格的 indexPath

我正在尝试如下所示。

@objc func addFruit(_ sender: UIButton) {
    let point = tableView.convert(sender.bounds.origin, to: sender)
    let indexPath = tableView.indexPathForRow(at: point)
}

但它一直为每个单元格返回 nil

还有其他方法可以从自定义按钮点击中获取 indexPath 吗?我添加了一个 demo project这里也是。

最佳答案

创建一个名为 SOButton 的自定义类,并向其添加 IndexPath 类型的变量。使用此类进行添加按钮初始化。

//Your class will look like - 

class SOButton: UIButton {
   var indexPath: IndexPath?
}

//Your action will look like -

@objc func addFruit(_ sender: SOButton) {
     print(sender?.indexPath.row)
}

//And in your cellForRow add

let addButton = SOButton(type: .custom)
addButton.indexPath = indexPath

希望这对你有帮助:)

关于ios - 从 UITableViewCell 的 accessoryView 中的自定义按钮获取索引路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47668940/

相关文章:

ios - swift 设置值 :forUndefinedKey:]: this class is not key value coding-compliant for the key

ios - Firebase queryOrderedbyChild 不返回 Null 值

ios - Xcode 11.0-swift 的 Core Plot iOS 编译器错误

ios - swift: 在调试中打印\r 字符

ios - 如何使 UITableView 标题可选择?

iphone - objective-c : How to only delete all file under a directory but keep the directory itself

ios - 架构设置为 64 位时图像不显示

iphone - 在具有多个部分的 UITableView 中进行 Segue,每个部分包含从单个数组中过滤的对象

ios - UITableViewCell在编辑模式下按减号后消失

ios - 如何更改 iOS 8 中选项卡栏图标的选定颜色?