1
我创建了custom cell
和以了解UISwitch
上的更改。我想我有我需要的一切,但我无法获得func didChangeSwitchState
被触发。Custom Cell with protocol to check in changes in UISwitch
VouchersViewController.swift
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:VouchersFilterCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! VouchersFilterCell
cell.delegate = self
cell.textLabel?.text = self.vouchersFilters[indexPath.row]
return cell
}
// MARK: - VouchersFilterCellDelegate
func didChangeSwitchState(sender: VouchersFilterCell, isOn: Bool) {
let indexPath = self.tableView.indexPath(for: sender)
debugPrint(indexPath?.row)
}
BaseCell.swift
class BaseCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// code common to all your cells goes here
setupViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setupViews(){
}
}
VouchersFilterCell.swift
protocol VouchersFilterCellDelegate: class {
func didChangeSwitchState(sender: VouchersFilterCell, isOn: Bool)
}
class VouchersFilterCell: BaseCell {
// MARK: - UIComponent
let titleLabel = UILabel()
let filterSwitch: UISwitch = {
let fSwitch = UISwitch()
fSwitch.addTarget(self, action: #selector(handledSwitchChange(sender:)), for: .valueChanged)
return fSwitch
}()
weak var delegate: VouchersFilterCellDelegate?
// MARK: - Life Cycle
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
// MARK: - Setup
override func setupViews() {
addSubview(titleLabel)
addSubview(filterSwitch)
addConstraintsWithFormat(format: "V:|-13-[v0]-13-|", views: titleLabel)
addConstraintsWithFormat(format: "H:|-16-[v0]-16-[v1]-16-|", views: titleLabel, filterSwitch)
addConstraintsWithFormat(format: "V:|-7-[v0]", views: filterSwitch)
}
// MARK: - IBAction
@IBAction func handledSwitchChange(sender: UISwitch) {
self.delegate?.didChangeSwitchState(sender: self, isOn:filterSwitch.isOn)
}
}
是否调用了'handledSwitchChange'? –
@RyanPoolos不,没有什么 – bruno
好,那么你的代表可能会很好。它看起来像你如何设置你的交换机。我注意到这个方法被标记为IBAction?但你正在代码中创建你自己的filterSwitch。你在使用Interface Builder吗? setupViews在哪里被调用? –