我有一个 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
。它看起来和工作正常。
现在我需要在用户点击此按钮时获取单元格的 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/