Наличие нескольких кнопок в пользовательском UITableViewCell - PullRequest
0 голосов
/ 24 октября 2019

Допустим, у меня есть 10 кнопок в пользовательском UITableViewCell. Как определить, какая кнопка нажата, и выполнить соответствующее действие обратно во ViewController, который содержит ячейку? Я ищу оптимистичное решение в кратчайшие сроки. Спасибо

Ответы [ 3 ]

0 голосов
/ 24 октября 2019

Код ячейки

final class MyCell: UITableViewCell {
    struct ConfiguringData {
        let action1: () -> Void
        let action2: () -> Void
    }
    @IBOutlet private weak var button1: UIButton!
    @IBOutlet private weak var button2: UIButton!

    private var didTapButton1Action: (() -> Void)?
    private var didTapButton2Action: (() -> Void)?

    @IBAction private func didTapButton1() {
        didTapButton1Action?()
    }
    @IBAction private func didTapButton2() {
        didTapButton2Action?()
    }

    func configure(with configuringData: ConfiguringData) {
        didTapButton1Action = configuringData.action1
        didTapButton2Action = configuringData.action2
    }
}

Код ViewController

class MyViewController: UIViewController {

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let myCell = tableView.dequeueReusableCell(withIdentifier: "MyCell") as! MyCell
        let action1 = { print("didTapButton1") }
        let action2 = { print("didTapButton2") }

        myCell.configure(
            with: MyCell.ConfiguringData(action1: action1, action2: action2)
        )

        return myCell
    }
}
0 голосов
/ 24 октября 2019

// Поместите этот код в ваш UITableViewDataSource: cellForRowAt

// Ячейка должна содержать эти кнопки, к которым вам нужно добавить do addTarget

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "currentTableViewCell", for: indexPath)
        as! CurrentTableViewCell

    cell.btn1.tag = 1
    cell.btn1.addTarget(self, action: #selector(buttonPressed(sender:)), for: .touchUpInside)

    cell.btn2.tag = 2
    cell.btn2.addTarget(self, action: #selector(buttonPressed(sender:)), for: .touchUpInside)

    cell.btn3.tag = 3
    cell.btn3.addTarget(self, action: #selector(buttonPressed(sender:)), for: .touchUpInside)

    return cell
}

@objc func buttonPressed(sender: UIButton) {

    let convertedPointInTable = sender.convert(CGPoint.zero, to:self.currentTableView)
    let retriveIndexPath = self.currentTableView.indexPathForRow(at: convertedPointInTable)
    print("In which cell \(retriveIndexPath!.row), which button pressed \(sender.tag)")
}
0 голосов
/ 24 октября 2019

** Есть два способа сделать это =:
Во-первых, вы можете создать коллекцию выходов кнопки IB и определить тег.
Второй Один такой же, но вместо того, чтобы собирать розетки, перейдите кНа раскадровке и при нажатии кнопки вы увидите там параметр тега, для каждой кнопки задайте свой тег (предположим, если у вас есть 10 кнопок, укажите тег от 1 до 10) here Поскольку вы делаете это в пользовательской ячейке,Вы можете либо выполнить вышеуказанные действия внутри класса UITableViewCell, либо вы также можете предварительно сформировать target в cellForRowAt, оба будут работать нормально

// Now inside your button action do this -:





   if sender.tag == 1{
    print("one")
    }
    if sender.tag == 2{
    print("two")
    }
             //OR (if inside cellForRowAt)
 cell.button.addTarget(self, action:#selector(handleRegister), for: .touchUpInside)

*so on...

// Убедитесь, что тип отправителя в IBAction должен быть UIButton

// Вы также можете поместить это в поле переключателей, просто базовое программирование *

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...