Reputation: 1945
Will someone please explain why the following code is not placing a button in my view?
Button Class
class CustomButton: UIButton {
var button = UIButton()
func makeButton() {
button.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
button.center = self.center
button.setTitle("PRESS", for: .normal)
button.backgroundColor = UIColor.red
button.addTarget(self, action: #selector(ViewController.buttonPressed), for: .touchUpInside)
self.addSubview(button)
}
}
Main Class
class ViewController: UIViewController {
var button: CustomButton?
override func viewDidLoad() {
super.viewDidLoad()
button?.makeButton()
}
@objc func buttonPressed() {
print("woohoo!")
}
}
Upvotes: 2
Views: 39
Reputation: 318804
You need to completely redo the CustomButton
class. It should not have a button
property. It should initialize itself.
And the setting of the target belongs in the view controller, not the button class.
Updated button code:
class CustomButton: UIButton {
init() {
super.init(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
setTitle("PRESS", for: .normal)
backgroundColor = UIColor.red
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Updated view controller:
class ViewController: UIViewController {
var button = CustomButton()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(button)
button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
}
@objc func buttonPressed() {
print("woohoo!")
}
}
Upvotes: 1