Juan
Juan

Reputation: 233

Adding a target to UIButton in UITableViewCell with didSet

I am trying to refactor my code and I can't seem to active the handleFavoriteStar() action from the SearchController when the button is tapped. I was following this video by LBTA on refactoring: https://youtu.be/F3snOdQ5Qyo

Formula Cell:

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
        }()
}

Search Controller:

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


     @objc func handleFavoritedStar() {
            print("Added to Favorites")
        }
}

Upvotes: 0

Views: 247

Answers (1)

Juan
Juan

Reputation: 233

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
    }

Upvotes: 0

Related Questions