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

问题描述 投票:0回答:1

我试图重构我的代码,当点击按钮时,我似乎无法激活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")
        }
}
ios swift uibutton refactoring didset
1个回答
0
投票
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
    }
© www.soinside.com 2019 - 2024. All rights reserved.