Swift 自定义回调不适用于第一个实例,但适用于第二个实例

问题描述 投票:0回答:0

我有以下自定义 UIStackViewComponent

class TitleWithSwitchView: UIStackView {
    let title: String
    var onSwitchTapped: ((Bool) -> Void)?
    override init(frame: CGRect) {
        self.title = ""
        super.init(frame: frame)
    }
    
    required init(coder: NSCoder) {
        self.title = ""
        super.init(coder: coder)
    }
    
    init(title: String) {
        self.title = title
        super.init(frame: .zero)
        setupUI()
        setupConstraints()
    }
    
    private var label: UILabel {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textColor = .white
        label.numberOfLines = 0
        label.lineBreakMode = .byWordWrapping
        label.text = "-"
        return label
    }
    
    private lazy var labelTitle = {
        let label = label
        label.text = title
        return label
    }()
    
    private lazy var switchButton = {
        let switchButton = UISwitch()
        switchButton.translatesAutoresizingMaskIntoConstraints = false
        switchButton.addTarget(self, action: #selector(switchTapped), for: .valueChanged)
        return switchButton
    }()
    
    @objc private func switchTapped() {
        onSwitchTapped?(switchButton.isOn)
    }
}

我有 2 个相同组件的实例,而开关仅适用于第二个实例。一开始没有任何反应

ios swift callback uiswitch
© www.soinside.com 2019 - 2024. All rights reserved.