Search code examples
swiftxcodeautolayout

Keeping buttons distance proportional to each other while scaling buttons


I have 2 buttons. Number 1 and number 2. I would like for them to stay a proportional distance away from each other no matter the device screen size. Similar to Figure 1

Because the buttons are diagonal from each other, auto layout does not allow me to set constraints to the closest button (At least to my understanding). For example, I cannot set the constraints of button 2 to button 1. It only gives the option to set the constraints based on the view.

I have set the buttons to scale like they currently do, but the buttons do not proportion themselves like I would want. When set to a smaller device the buttons are to far away from each other(Figure 2). When set to a larger device the buttons overlap(Figure 3).

I have tried to use the multiplier feature for the leading and top constraints but it seems to not have any effect.

Thanks

Figure 1

Figure 1

Figure 2

enter image description here

Figure 3

enter image description here


Solution

  • Constrain your second view's horizontal center and vertical center to the first view's, the constant you set here does not matter but I suggest setting it to how you expect the views to be spaced just so it looks correct in your Storyboard. Create an outlet to both of those constraints in your view controller. In your controller's viewDidLayoutSubviews() update each constraint's constant to it's matching axis(x = width, y = height).

    @IBOutlet weak var secondViewCenterXConstraint: NSLayoutConstraint!
    @IBOutlet weak var secondViewCenterYConstraint: NSLayoutConstraint!
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        secondViewCenterXConstraint.constant = secondView.frame.size.width
        secondViewCenterYConstraint.constant = secondView.frame.size.height
    }
    

    centerXConstraint centerYConstraint iphone ipad

    You'll see in my screen shots I have the second view's top left corner matching the bottom right corner of the first view. If you want to space them more similar to what you have in your screen shot then you could use something like below. I'm just taking a guess on the calculations, you'll have to edit them according to the spacing you want to accomplish. But all calculations you make for these constants should be based on some kind of multiplier of the view's width and height.

    secondViewCenterXConstraint.constant = secondView.frame.size.width * 0.9
    secondViewCenterYConstraint.constant = secondView.frame.size.height * 0.5
    

    I created a repo to better show my example.