Reputation: 333
I was wondering if someone could help me with programatically constraints. What I want is:
I create buttons inside a loop and the buttons are aligned horizontally next to each other. Some of the buttons have different widths, so that means that a button can overlap to another button. Is is possible to use constraint to prevent the overlapping and add a white space in between?
Thanks in advance
Code:
for (j, _) in buttonInfo.enumerated(){
let button: UIButton = buttonArray[j]
let stackView = UIStackView();
stackView.spacing = 30;
button.tag = Int((buttonInfo[j]?.pID)!)!
button.setTitle(buttonInfo[j]?.title, for: .normal)
button.addTarget(self, action: #selector(PalletViewController.productCall), for: .touchUpInside)
let stock = Int(buttonInfo[j]!.stock)
if(stock! == 0 || stock! < 0){
button.isHidden = true;
}
let views = ["view": view, "button": button] as [String : Any]
let spacing = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(10)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views);
view.addConstraints(spacing);
}
Upvotes: 0
Views: 1026
Reputation: 30
Stack view is best option, you can create it programmatically also. https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/LayoutUsingStackViews.html
Upvotes: 1