Reputation: 43
I am currently making a calculator and want to change the size of my 0
button to the size of 2 subviews - which is half the size of the entire view. I want it to look exactly like apples calculator app, where the 0
is bigger than all the other buttons.
The way i layout my view is by having a vertical UIStackView
and adding horizontal UIStackView
's to it, just like the picture below.
Therefore, i want the last horizontal stack to have 3 arranged subviews but make the 0
button fill the exceeding space, so the ,
and =
buttons are the same size as all other buttons.
Thank you.
Upvotes: 0
Views: 840
Reputation: 602
Programmatically, you could set multiplier with constraint(equalTo:multiplier:)
, official docs: https://developer.apple.com/documentation/uikit/nslayoutdimension/1500951-constraint
So we could constraint the last two button with same width and make the first one two times longer than one of the other two.
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
let btn1 = UIButton()
let btn2 = UIButton()
let btn3 = UIButton()
btn1.backgroundColor = .red
btn2.backgroundColor = .yellow
btn3.backgroundColor = .blue
let hStack = UIStackView(arrangedSubviews: [btn1, btn2, btn3])
hStack.axis = .horizontal
hStack.spacing = 1
view.addSubview(hStack)
hStack.translatesAutoresizingMaskIntoConstraints = false
hStack.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
hStack.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
hStack.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
// Here would be what you need:
btn2.widthAnchor.constraint(equalTo: btn3.widthAnchor).isActive = true
btn1.widthAnchor.constraint(equalTo: btn2.widthAnchor, multiplier: 2).isActive = true
}
Upvotes: 1
Reputation: 15748
You can use stackview.distribution = .fillEquallly for first 4 horizontal stackviews and use stackview.distribution = .fillPropotionally for the last horizontal stackview.
Then set with constraint for the 0 button to 50% of last horizontal stackview's width.
Upvotes: 1