具有协议的自定义单元格,用于检查UISwitch中的更改

时间:2017-04-18 17:07:35

标签: ios swift uitableview uiswitch

我创建了custom cellprotocol,以了解UISwitch上的更改。我认为我拥有所需的一切,但我无法触发功能didChangeSwitchState

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

1 个答案:

答案 0 :(得分:2)

正如我们在评论中一起想出的那样,似乎在自己准备好之前创建了一个let属性,因此Switch目标为零。更改为lazy var可确保首先创建self。

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