2017-04-18 112 views
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) 
    } 
} 
+0

是否调用了'handledSwitchChange'? –

+0

@RyanPoolos不,没有什么 – bruno

+1

好,那么你的代表可能会很好。它看起来像你如何设置你的交换机。我注意到这个方法被标记为IBAction?但你正在代码中创建你自己的filterSwitch。你在使用Interface Builder吗? setupViews在哪里被调用? –

回答

2

正如我们似乎意见一起想出像创建一个让财产在自己准备好之前,Switch目标是零。更改为惰性变量可确保首先创建自我。

lazy var filterSwitch: UISwitch = { 
    let fSwitch = UISwitch() 
    fSwitch.addTarget(self, action: #selector(handledSwitchChange(sender:)), for: .valueChanged) 
    return fSwitch 
}() 
+1

我一直以'lazy var'来完成我的视图,因为我不相信Swift 1.0允许我们这样设置。所以这从来没有发生过我。但它绝对是非常好的知道! –