1

I have designed a UIStackView in a StoryBoard and I have added 2 UIbutton with a height contraint set at 70. My stackview is set to vertical fill and has some constraints set on the storyboard to fit in the Controller's View.

I have added an outlet from the stackView and from the UIbutton. I am trying to add a third UIButton programatically in the stack View

@IBOutlet weak var Btn1: UIButton!

@IBOutlet weak var myStackView: UIStackView!

var accounts = [Account]()

override func viewDidLoad() {
    super.viewDidLoad()
    Btn1.setTitle("Name", for: .normal)

    let Btn3 = UIButton(frame: CGRect(x: 0, y: 110, width: 100, height: 50))
    Btn3.setTitle("Btn3", for: .normal)
    Btn3.heightAnchor.constraint(equalToConstant: 70).isActive = true
    myStackView.addArrangedSubview(Btn3)

But Btn3 never appears

user3239711
  • 639
  • 1
  • 7
  • 24

1 Answers1

1

Well, assuming that your background color is default-white, the button is there, it's just hard to see ;). In other words: its title color is white.

Try setting some colors:

Btn3.backgroundColor = UIColor.yellow
Btn3.setTitleColor(UIColor.red, for: .normal)

You could also create it as a system button if you care about tintColor:

let Btn3 = UIButton(type: .system)

If you create a button using init(frame:), you get a custom button and the tintColor documentation has this to say:

This property has no default effect for buttons with type custom. For custom buttons, you must implement any behavior related to tintColor yourself.

Also, rather than specifying a meaningless frame (layout is managed by the stack view anyway) when initializing the button using init(frame:), I'd suggest using .zero:

let Btn3 = UIButton(frame: .zero)

And a final note regarding Swift naming conventions:

Follow case conventions. Names of types and protocols are UpperCamelCase. Everything else is lowerCamelCase.

So Btn3 suggests a type, while btn3 or loginButton suggests a variable. See "Follow case conventions" in the Swift API Design Guidelines.

thm
  • 1,217
  • 10
  • 12
  • Definitely a stupid error ! And no problem with camel case of course, I messed up when typing the example code. – user3239711 May 24 '17 at 08:45
  • Don't be too hard on yourself, I guess everybody has their fair share of "duh!" moments :). For cases like these I recommend Xcode's "Debug View Hierarchy" feature by the way. Also, please consider accepting this as the answer if it solved your problem. – thm May 24 '17 at 09:53