Swift custom callback is not working on first instance but working on second instance

62 views Asked by At

I have following custom 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)
    }
}

I have 2 instance of same component and the switch is only working on second instance. On first instance nothing happens

Update :

This is how I'm using this component. The second one works perfectly but the first one is not working

    private lazy var stackViewHobbyContainer = {
            let stack = TitleWithSwitchView(title: "Some Text")
            stack.onSwitchTapped = { [weak self] isOn in
                self?.onHobbyContainerSwitchChange(isOn: isOn)
            }
            return stack
        }()

private lazy var stackViewChallengeSwitchView = {
        let stack = TitleWithSwitchView(title: "Another Text?")
        stack.onSwitchTapped = { [weak self] isOn in
            print("Switch tapped \(isOn)")
        }
        return stack
    }()
0

There are 0 answers