使用didSet将目标添加到UITableViewCell中的UIButton

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用didSet将目标添加到UITableViewCell中的UIButton相关的知识,希望对你有一定的参考价值。

我试图重构我的代码,当点击按钮时,我似乎无法激活SearchController中的handleFavoriteStar()动作。我正在关注LBTA关于重构的视频:https://youtu.be/F3snOdQ5Qyo

公式细胞:

class FormulasCell: UITableViewCell {
    var searchController: SearchController! {
            didSet {
                buttonStar.addTarget(searchController, action: #selector(searchController.handleFavoritedStar), for: .touchUpInside)
            }
        }
        var buttonStar: UIButton = {
            let button = UIButton()
            button.setImage( #imageLiteral(resourceName: "GrayStar") , for: .normal)
            button.tintColor = UIColor.greyFormula
            button.translatesAutoresizingMaskIntoConstraints = false
            return button
        }()
}

搜索控制器:

class SearchController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        let formulaCell = FormulasCell()
        formulaCell.searchController = self
        setupTableView()
    }


     @objc func handleFavoritedStar() {
            print("Added to Favorites")
        }
}
答案
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! FormulasCell
        cell.selectionStyle = .none
        cell.searchController = self
        return cell
    }

以上是关于使用didSet将目标添加到UITableViewCell中的UIButton的主要内容,如果未能解决你的问题,请参考以下文章