使用 didSet 向 UITableViewCell 中的 UIButton 添加目标
Adding a target to UIButton in UITableViewCell with 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")
}
}
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
}
我正在尝试重构我的代码,但我似乎无法在点击按钮时从 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
}