Для доступа к ячейке Tableview в действии Button - PullRequest
0 голосов
/ 13 октября 2019

Я хочу удалить ячейку таблицы, нажав кнопку, присутствующую в той же ячейке. Но я не могу получить доступ к ячейке в функции действия кнопки. Пожалуйста, помогите мне получить доступ к этой ячейке. Мой код -

class MatchesViewController: UIViewController{

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

    guard let cell = tableView.dequeueReusableCell(withIdentifier: "MatchingUsersTVCell") as? MatchingUsersTVCell else{
        return UITableViewCell()
    }
    let likeUid = userIdArray[indexPath.row]

    cell.heartBtn.tag = indexPath.row

    cell.heartBtn.addTarget(self, action: #selector(userLikeButtonWasTappaed(sender:)), for: .touchUpInside)
    }

    @objc func userLikeButtonWasTappaed(sender: UIButton){
        if let cell = sender.superview as? MatchingUsersTVCell{
            CellAnimator.animate(cell: cell)
        }
        let tag = sender.tag
        let userid = userIdArray[tag]
    }
}

Ответы [ 3 ]

1 голос
/ 13 октября 2019

Я бы избегал использования тегов и вместо этого реализовывал протокол / делегат. Использование indexPath позволяет использовать несколько разделов и т. Д. *

1) Создать протокол:

protocol MatchingUsersTVCellDelegate : class {
    func didTapLikeButton(_ indexPath: IndexPath)
    func didTapOtherButton(_ indexPath: IndexPath)
}

2) Создать / обновить ячейку:

class MatchingUsersTVCell : UITableViewCell {
    weak var delegate: MatchingUsersTVCellDelegate?   
    var indexPath: IndexPath!
    // add target to your like button
    func didTapLIkeButton(_ sender: UIButton) {
        self.delegate?.didTapLikeButton(indexPath)
    }
    func didTapOtherButton() {
        self.delegate?.didTapOtherButton(indexPath)
    }
}

3) убедитесь, что ваш viewController соответствует новому делегату:

extension YourViewController: MatchingUsersTVCellDelegate {
    func didTapLikeButton(_ indexPath: IndexPath) {
        //Do something with the indexPath or indexPath.row
        dataSource.remove(at: indexPath.row)
    }
    func didTapOtherButton(_ indexPath: IndexPath) {
        //Do something else with the indexPath or indexPath.row
    }
}

4) Установите делегат и indexPath

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell...
    cell.delegate = self
    cell.indexPath = indexPath
    return cell
}
0 голосов
/ 14 октября 2019

вы можете получить это так в вашем методе выбора

@objc func userLikeButtonWasTappaed(button:UIButton){
guard let indexPath = myTableView.indexPathForRow(at: button.convertPoint(button.frame.origin, toView: myTableView)) else {
    print("Error: indexPath)")
    return
}

print("indexPath.row: \(indexPath.row)")
}
0 голосов
/ 13 октября 2019

В MatchingUsersTVCell добавьте два свойства, одно с именем parentVC типа UIViewController и одно с именем index типа Int:

class MatchingUsersTVCell: UITableViewCell {
    var parentVC: UIViewController!
    var index: Int!

    ...

}

Затем при создании каждой ячейкиустановите эти два значения соответствующим образом:

class MatchesViewController: UIViewController, UITableViewDelegate, UITableViewDatasource {

    ...

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "MatchingUsersTVCell") as? MatchingUsersTVCell else {
            return UITableViewCell()
        }
        cell.parentVC = self
        cell.index = index

        ...

        return cell
    }
}

Теперь вы просто обновите источник данных tableView вашего parentVC и перезагрузите его данные при каждом нажатии кнопки:

class MatchingUsersTVCell: UITableViewCell {

    ...

    @objc func userLikeButtonWasTappaed(sender: UIButton){
        parentVC.userIdArray.remove(at: index)
        parentVC.tableView.reloadData()
    }

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