In the app I am currently building, I decided the square button I have in one corner looks too small on an iPad screen, but it’s OK on an iPhone screen. The button is drawn by a PaintCode style kit so resizing it, in general, wasn’t going to be a problem. But, I wondered, how could I go about the resizing?
My first attempt almost worked. I had two constraints on the button to put it 8 points from the bottom and 8 points from the left, and those had to remain. I then replaced the fixed width and height constraints with an aspect ratio constraint of 1:1 and a width constraint relating to the container view with a constant of zero and a multiplier of 0.1 to make the button 10% of the width of the screen. The greater than or equal relationship, I will admit, was experimental. But it worked. Well, it worked until I rotated the device to landscape and the button suddenly grew in size! The width in landscape is considerably larger. I couldn’t have this. The button should be sized for the device, regardless of orientation. I realised at this point it was going to take some code to “find the shortest side.” But how to apply that?
A quick foray into Stack Overflow yielded no obvious answers so I asked my own question. The answer I got was super simple.
I left the aspect ratio constraint in place and set a simple width = 32 constraint (the smallest size it will ever be, given the 320 point screen width on early iPhones). Then I Control-dragged that constraint to an IBOutlet in my ViewController. I had no idea you could do this! Then it was a simple case of calculating my desired button size in viewDidLoad( ) and updating the constraint which I now have easy access to.
let buttonWidth = 0.1 * (self.view.bounds.width < self.view.bounds.height ? self.view.bounds.width : self.view.bounds.height) widthConstraint.constant = buttonWidth self.view.layoutIfNeeded()