Элементы ячейки просмотра таблицы не могут щелкнуть и получить данные

#ios #swift #uitableview

#iOS #swift #uitableview

Вопрос:

У меня есть одно табличное представление, и внутри него я разместил одно основное представление. И внутри этого основного представления я разместил одну кнопку.И когда когда-либо будете использовать, нажмите на кнопку «Моя ячейка». Мне нужно получить метку заголовка ячейки.Это то, что мне нужно. Но я попробовал следующий приведенный ниже код. Не уверен, что я упускаю. Это вообще не вызывает мою ячейку.добавьте целевую строку.

Код в ячейке для строки в индексе:

 cell.cellBtn.tag = indexPath.row
cell.cellBtn.addTarget(self, action:#selector(self.buttonPressed(_:)), for:.touchUpInside)

@objc func buttonPressed(_ sender: AnyObject) {
    print("cell tap")
    let button = sender as? UIButton
    let cell = button?.superview?.superview as? UITableViewCell
    let indexPath = tableView.indexPath(for: cell!)
    let currentCell = tableView.cellForRow(at: indexPath!)! as! KMTrainingTableViewCell
    print(indexPath?.row)
    print(currentCell.cellTitleLabel.text)
}
  

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

Пробовал и с закрытием. В ячейке для строки по индексу:

 cell.tapCallback = {
    print(indexPath.row)
}
  

В моей ячейке табличного представления:

 var tapCallback: (() -> Void)?
@IBAction func CellBtndidTap(_ sender: Any) {
    print("Right button is tapped")
    tapCallback?() 
}
  

Здесь этот оператор печати получает печать в консоли.

Комментарии:

1. используйте любой из них…

2. я попробовал только два решения по-разному. Не в одно и то же время

3. почему вы используете AnyObject в качестве параметра, если это UIButton?

4. возможно ли прикрепить ваш peoject

5. @david подтвердите с вашего конца, что в методе cell for row вы использовали какое-либо условие if или guard или любой обработчик завершения. И вы добавили свою строку в соответствии с этими упомянутыми условиями. Может быть, если вы напишете внутри, это не вызовет. Как вы упомянули, вы проверили с помощью точки останова.

Ответ №1:

 import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    var list = [String]()
    @IBOutlet weak var tableView: UITableView!

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return list.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyTableViewCell
        cell.saveButton.tag = indexPath.row
        //cell.saveButton.accessibilityIdentifier = "some unique identifier"
        cell.tapCallback = { tag in
            print(tag)
        }
        return cell
    }
}

class MyTableViewCell: UITableViewCell {
    // MARK: - IBOutlets
    @IBOutlet weak var saveButton: UIButton!

    // MARK: - IBActions
    @IBAction func saveTapped(_ sender: UIButton) {
        tapCallback?(sender.tag)
    }

    // MARK: - Actions
    var tapCallback: ((Int) -> Void)?
}
  

Комментарии:

1. Теги в этом случае бессмысленны. Путь к индексу фиксируется при закрытии.

Ответ №2:

На самом деле это не очень хорошая практика программирования — добавлять целевое действие кнопки (которая содержится в ячейке табличного представления) в контроллер представления. Для этого мы должны следовать подходу, ориентированному на протокол. Пожалуйста, попытайтесь понять концепцию.

 /*This is my cell Delegate*/
protocol InfoCellDelegate {
    func showItem(item:String)
}


/*This is my cell class*/
class InfoCell: UITableViewCell {
    //make weak reference to avoid the Retain Cycle
    fileprivate weak var delegate: InfoCellDelegate?

    //Outlet for views
    @IBOutlet var showButton: UIButton?

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

    //This is the public binding function which will bind the data amp; delegate to cell
    func bind(with: DataModel?, delegate: InfoCellDelegate?, indexPath: IndexPath) {
        //Now the bind the cell with data here
        //.....
        //Assign the delegate
        self.delegate = delegate
    }

    //Button action
    @IBAction func rowSelected(sender: UIButton) {

        self.delegate?.showItem(item: "This is coming from cell")
    }
}


/*Now in your ViewController you need to just confirm the InfoCellDelegate amp; call the bind function*/
class ListViewController: UIViewController {
     //Views initialisation amp; other initial process
}

//Table view Delegate amp; Data source
extension ListViewController: UITableViewDataSource, UITableViewDelegate {
    /**
    Configure the table views
    */
    func configureTable() {

        //for item table
        self.listTable.register(UINib.init(nibName: "(InfoCell.classForCoder())", bundle: nil), forCellReuseIdentifier: "(InfoCell.classForCoder())")
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "InfoCell") as! InfoCell

        cell.bind(with: DataModel, delegate: self, indexPath: indexPath)

        return cell
    }
}

extension ListViewController: InfoCellDelegate {
    func showItem(item) {
        print(item)
    }
}