1

I have a problem where when I add a button from a closure the function does not execute:

Here I create the button (Close Button):

private let CloseButton: UIButton = {
         let button = UIButton(type: .system)
         button.setTitle("X", for: .normal)
         button.translatesAutoresizingMaskIntoConstraints = false
         button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 34)
         button.setTitleColor(.red, for: .normal)
         button.addTarget(self, action: #selector(closeTest), for: .touchUpInside)
         return button
     }()

Here is the function:

@objc private func closeTest(_ sender: UIButton) {
         print("Test")
     }

Here are the constraints:

topContainer.addSubview(CloseButton)
CloseButton.centerXAnchor.constraint(equalTo: topContainer.centerXAnchor).isActive = true
CloseButton.centerYAnchor.constraint(equalTo: topContainer.centerYAnchor).isActive = true
CloseButton.heightAnchor.constraint(equalTo: topContainer.heightAnchor, multiplier: 0.8).isActive = true
Christophe
  • 68,716
  • 7
  • 72
  • 138
mick1996
  • 516
  • 9
  • 31
  • 1
    can't reproduce please share how you add `topContainer` ? Also does it work any other way than closure ? – Shehata Gamal Jan 11 '20 at 18:37
  • 1
    @mick1996 yes it problem with topContainer and where this add subview code u r calling from ? . because it seems fine to me. – TheCodeTalker Jan 11 '20 at 20:58
  • 1
    You cannot set a button target to self when initializing an instance property of self, because self is exactly what does not yet exist. I regard it as a bug that the compiler does not stop you. Add `lazy` to make this work. `private lazy var CloseButton` – matt Jan 11 '20 at 21:48

0 Answers0