I want to add a subview (UIButton) in my custom view. However, when I do addSubview() in my created function, it won't add the UIButton, even when I call setNeedsLayout(). I call the addButton() in the ViewController
class PlayingField: UIView {
var buttons: [UIButton] = []
func addButton() {
let button = UIButton()
addSubview(button)
buttons.append(button)
setNeedsLayout()
layoutIfNeeded()
}
override func layoutSubviews() {
for i in buttons.indices {
buttons[i].frame = CGRect(x: 50, y: 50, width: 100, height: 100)
buttons[i].backgroundColor = UIColor.green
}
}
}