I have a scroller at the bottom of my view controller which contains buttons. Buttons are not always active, they change as the user adds them to his favourites. Which means I have to decide on the x position of the buttons programmatically.
What I have done is created outlets of all the buttons from the view controller in the storyboard to the script and I am attempting to access them like this (simplified code):
var Items = [String : Bool]
@IBOutlet weak var item1: UIButton!
...
if Items[item] == true {
item1.isEnabled = true
\\ here comes a line of code where i should position item1's x position but I haven't managed to find the right way
}
The question is how to change the x position of UIButton programmatically, and are there better ways to handle the problem? I am using Xcode 8 and swift 3
EDIT :
Method for constraints:
func activeConstraint(element: UIButton, constant: Int) {
let widthConstraint100 = NSLayoutConstraint(item: element,
attribute:NSLayoutAttribute.width,
relatedBy:NSLayoutRelation.equal,
toItem:nil,
attribute:NSLayoutAttribute.notAnAttribute,
multiplier:1.0,
constant: 100)
let widthConstraint0 = NSLayoutConstraint(item: element,
attribute:NSLayoutAttribute.width,
relatedBy:NSLayoutRelation.equal,
toItem:nil,
attribute:NSLayoutAttribute.notAnAttribute,
multiplier:1.0,
constant: 0)
if constant == 0 {
element.removeConstraint(widthConstraint100)
element.addConstraint(widthConstraint0)
} else {
element.removeConstraint(widthConstraint0)
element.addConstraint(widthConstraint100)
}
element.updateConstraints()
}
Example of call to the function:
if Items[item] == true {
activeConstraint(element: item, constant: 100)
} else {
activeConstraint(element: item, constant: 0)
}
EDIT 2:
Although I have seen many questions here referring UIStackView (like this one), none of the solutions worked for me. I have an horizontal scroller at the bottom of the screen with many buttons that get activated or deactivated programmatically with their width constraint set to 0 or 100. Here is the final result that works in my case (XCode 8.0) :
Hierarchy: image
UIScrollView HAS to have one element: View (lets call it Container View) that holds all the contents of the scroller. Container view needs to have 4 constraints - top, bottom, leading and trailing set towards superView (UIScrollView). (preferably all 4 set to 0). Also set vertical constraint to center horizontally from Container view to superView - UIScrollView.
StackView holds all the buttons - it needs to have all 4 constraints (top, bottom, leading, trailing) set towards superView which is Container View.
All buttons need to have their width constraint set to a constant of desire.