I have a UIScrollView set up, and am using addSubView to add 5 buttons to it. Here is the code inside my viewDidLoad.
let codedButton:UIButton = UIButton(frame: CGRectMake(0, 0, 100, 50))
codedButton.backgroundColor = UIColor.redColor()
codedButton.setTitle("Button 1", forState: UIControlState.Normal)
codedButton.addTarget(self, action: #selector(ViewController.buttonAction(_:)), forControlEvents: UIControlEvents.TouchUpInside)
codedButton.tag = 1
self.buttonScrollView.addSubview(codedButton)
let codedButton2:UIButton = UIButton(frame: CGRectMake(110, 0, 100, 50))
codedButton2.backgroundColor = UIColor.redColor()
codedButton2.setTitle("Button 2", forState: UIControlState.Normal)
codedButton2.addTarget(self, action: #selector(ViewController.buttonAction(_:)), forControlEvents: UIControlEvents.TouchUpInside)
codedButton2.tag = 2
self.buttonScrollView.addSubview(codedButton2)
(all the way to 5.)
The problem that I need help with is... Ultimately, these buttons will be dynamically displayed. Not just a set amount of 5.
How do I adjust the X value of the CGRectMake to automatically "float" new buttons to the right of the button that was just created? In my code above, I am explicitly stating where the X is, but that won't work properly once these buttons become dynamically created in code.
EDIT To clarify my question above: I have attached an image. Note how the buttons always stack horizontally / next to each other, regardless of if there's 2 3 4 or 5. These buttons will be dynamically shown. Therefore, with my code attempt I have provided above, it will not work because it is explicitly setting where to place the buttons on the X axis.
I see that you are doing this programmatically. I can't help with the code, but stack views in the storyboard are great. I have a feature in my app where I have 4 buttons, but the user may only see, say, 2 of the 4 buttons.
1) Add the buttons horizontally into the storyboard (They don't need to be perfectly aligned, just enough so that Xcode can recognize it's horizontal rather than vertical.
2) Select all 5 buttons
3) Click on the stack view button in the lower right-hand corner of Xcode (The button with 4 horizontal lines with and an arrow pointing down.
4) In the attributes inspector, choose horizontal as the axis, alignment as center, fill proportionately, play with the spacing, and choose scale to fill as the mode.
5) In the Swift file, you can add or hide the buttons using button.hidden = true / false
NOTE: Keep in mind that stack views are only available with iOS 9 when I last checked