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

时间:2019-02-07 02:38:02

标签: ios swift uibutton refactoring didset

我正在尝试重构我的代码,点击按钮时似乎无法从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")
        }
}

1 个答案:

答案 0 :(得分: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
    }