Arthur_Geek
Arthur_Geek

Reputation: 13

UIStackView can't show UIView when UIView added dynamically

@IBAction func addNewImage(sender: UIButton) {
    let rect = CGRectMake(0, 0, 30, 30)
    let myView = UIView(frame: rect)
    myView.backgroundColor = UIColor.greenColor()
    myView.alpha = 1.0
    myStackView.addArrangedSubview(myView)
}

This code above is just an action triggered by a button. All I want to do is just add a new UIViewto the UIStackView which is named myStackView here, and finally I found the stackView re-layout all the arrangedViews but the newly added view can't be seen, I don't know why.

Thank you for your great answers below.

Upvotes: 1

Views: 919

Answers (1)

Satheesh
Satheesh

Reputation: 11276

Try this,

@IBAction func buttonPressed(sender: AnyObject) {

    let rect = CGRectMake(0, 0, 30, 30)
    let myView = UIView(frame: rect)
    myView.backgroundColor = UIColor.greenColor()
    myView.alpha = 1.0
    myView.heightAnchor.constraintEqualToConstant(20).active = true
    myView.widthAnchor.constraintEqualToConstant(20).active = true
    myStackView.addArrangedSubview(myView)

}

It should work.

Upvotes: 3

Related Questions