da32
da32

Reputation: 743

Center UILabel inside UIView in Stack View

I have a horizontal stack view arranged in storyboard. As for the views for the stack view, it is done programatically since the number of views inside the stack view is dynamic. I've set the stack view to be 'Fill Equally'.

For the views inside, there will be a UIlabel. The problem that I have is that I can't center the UILabel inside the UIView which will be added into the stack view.

Here is my code:

    let main1 = UIView()
    main1.backgroundColor = UIColor.red
    stackView.addArrangedSubview(main1)

    let text1 = UILabel()
    text1.text = "Lvl 1"
    text1.textColor = .blue
    text1.textAlignment = .center
    text1.backgroundColor = .yellow
    text1.sizeToFit()
    main1.addSubview(text1)


    let label2 = UIView()
    label2.backgroundColor = UIColor.blue
    stackView.addArrangedSubview(label2)

For this example, I'm only adding 2 view, with the label added to the first view. So, how can I center the UILabel which will be inside of each UIView?

Upvotes: 0

Views: 1123

Answers (1)

gulyashki
gulyashki

Reputation: 459

You can use autolayouts to achieve this. Check the code below:

...

main1.addSubview(text1)

text1.translatesAutoresizingMaskIntoConstraints = false
text1.centerXAnchor.constraint(equalTo: main1.centerXAnchor).isActive = true
text1.centerYAnchor.constraint(equalTo: main1.centerYAnchor).isActive = true

Upvotes: 2

Related Questions