あなたがここにいくつかの可能性を持っては何です。 それらのうちの1つは、タグを使用するのが最も簡単です。
完全なソリューションを提供するには、まずcellForRowAtIndexPath
メソッドでボタンにタグを追加する必要があります。
func handleButtonTapped(sender: UIButton) {
// Now you can easily access the sender's tag, (which is equal to the indexPath.row of the tapped button).
// Access the selected cell's index path using the sender's tag like so :
let selectedIndex = IndexPath(row: sender.tag, section: 0)
// And finally do whatever you need using this index :
tableView.selectRow(at: selectedIndex, animated: true, scrollPosition: .none)
// Now if you need to access the selected cell instead of just the index path, you could easily do so by using the table view's cellForRow method
let selectedCell = tableView.cellForRow(at: selectedIndex) as! YourCustomCell
}
もう一つの可能性、クロージャを使用することになります
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: yourReuseIdentifier, for: indexPath) as! YourCustomCell
// Set your button tag to be equal to the indexPath.row:
cell.button.tag = indexPath.row
// Add a target to your button making sure that you return the sender like so:
cell.button.addTarget(self, action: #selector(handleButtonTapped(sender:)), for: .touchUpInside)
}
そして今、これはあなたのhandlerButtonTapped()
メソッド内のように、それがどのように見えるかです。
のUITableViewCellのサブクラスを作成します。
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// ...
cell.shouldSelectRow = { (selectedCell) in
// Since you now know which cell got selected by the user, you can access via its index path:
let selectedIndex = self.tableView.indexPath(for: selectedCell)
// Do whatever you need using the selected cell here
self.tableView.selectRow(at: selectedIndex, animated: true, scrollPosition: .none)
}
// ...
}
注:あなたはまた、デリゲートを使用することができ
class CustomTableCell: UITableViewCell {
var shouldSelectRow: ((CustomTableCell) -> Void)?
// MARK: User Interaction
@IBAction func handleDidTapButton(_ sender: UIButton) {
// Call your closure whenever the user taps on the button:
shouldSelectRow?(self)
}
}
今、あなたは、このようなあなたのcellForRowAtIndexPath
方法を設定することができます。
そして、それは同様に動作します:)
の
可能な複製([私はcell.swiftでindexPath.rowを取得できますか] https://stackoverflow.com/questions/40437550/how-can-i- get-indexpath-row-in-cell-swift) – matiastofteby