Вы можете создать подкласс UIButton
и добавить свойство index
, в котором вы можете сохранить представленный индекс для кнопки:
import UIKit
class UIButtonWithIndex: UIButton {
var representedIndex: Int?
}
Затем вам следует использовать этот класс в раскадровке вместо UIButton
.
После этого добавьте кнопку в качестве розетки в вашу ячейку и подключитесь в Интерфейсном Разработчике.
class CustomCell: UITableViewCell {
@IBOutlet weak var button: UIButtonWithIndex!
var buttonAction: ((UIButtonWithIndex) -> Void)?
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
@IBAction func activeInactive(_ sender: UIButtonWithIndex) {
self.buttonAction?(sender)
}
// Reset the represented index when reusing the cell
override func prepareForReuse() {
//Reset content view width
button.representedIndex = nil
}
}
Затем при снятии очереди с ячейки в cellForRowAt indexPath
установите свойство representedIndex
.Теперь в вашем buttonAction вы должны иметь индекс строки, в которой была нажата кнопка.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reusableCell", for: indexPath) as! CustomCell
let data = items[indexPath.row]
cell.displayProductName.text = data.productName
cell.button.representedIndex = indexPath.item
cell.buttonAction = { sender in
print("Button tapped... \(sender.representedIndex)")
}
return cell
}
Получив индекс, вы можете получить ячейку с помощью cellForRowAtIndexPath