узнать индекс ячейки на которую тапнул пользователь Swift

Возник такой вопрос Я разместил TableViewController на ViewController

Хочу обратится к tableView, чтобы у него вызвать indexPathForSelectedRow, но он не находит tableView

Что можно сделать в такой ситуации?

Хотел вызвать этот метод, что бы узнать индекс ячейки на которую тапнул пользователь


Ответы (1 шт):

Автор решения: Oleg Soloviev

Вот пример стандартного кода, с обработкой tableView.indexPathForSelectedRow:

final class ViewController: UIViewController {

    @IBOutlet private weak var tableView: UITableView!
    
    private let cellIdentifier = "Cell"
    private var data = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.delegate = self
        tableView.dataSource = self

        data.append("Hello")
        data.append("World")
    }

}

extension ViewController: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
        cell.textLabel?.text = data[indexPath.row]

        return cell
    }
}

extension ViewController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        debugPrint(tableView.indexPathForSelectedRow ?? "Empty")
    }
}
→ Ссылка