私はUISearchController
を持っています。UITableViewController
はsearchResultsController
です。UITableViewCellのアクセサリービューのカスタムボタンからインデックスパスを取得
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
}
}
検索結果が表示されるセルにカスタムボタンを表示する必要があります。だから私はを細胞 '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を追加しました。
try 'let cell = sender.superview?.superview as? CustomTableViewCell let indexPath = tblView.indexPath(for:cell!) ' –