Making UIButton a % of the screen

I noticed certain button sizes look great on one the iPhone 5 simulator but do not look as good on the iPhone 6 simulator and this is because the heights or constraints that I place on the UIButtons end up leaving a lot of blank space down the bottom of my App Screen.


I would like to have a button that is 40% of the screen size regardless of what device I am simulating on.


Any ideas on how to make the size of the button stay 40% of the screen size regardless of the device?

Accepted Answer

There are multiple ways to accomplish this. However, depending on if you need the constraint for multiple orientations, this is not the best solution and I would recommend checking out building the constraints programmically: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/AutoLayoutinCode/AutoLayoutinCode.html#//apple_ref/doc/uid/TP40010853-CH11-SW1


But, a simple and quick method to do this would be to create a CGRect and dynamically frame the button inside of that. Here's some code to do that:


        let myButton = UIButton()
        myButton.frame = CGRectMake(0, self.view.frame.height * 0.6, self.view.frame.width, self.view.frame.height)
        myButton.backgroundColor = UIColor.blackColor()
        self.view.addSubview(myButton)


This should be a step in the right direction for you.

If you make an "equal width" constraint from your button to your view in IB, you can then edit that constraint to change the multiplier from 1 (the default) to 0.4 or whatever you like. Then your button's size will be a fixed fraction of the view's size.


Of course I'm assuming here that you do actually want "a button that is 40% of the screen size" like you said. If what you actually meant was that you want your button *positioned* at 40% of the screen size, then you would add an extra view just for resizing purposes, give it an equal width / height constraint to superview and adjust the multiplier to the desired fraction, then align your button (center, top, whatever you like) to the extra view's edge.

Making UIButton a % of the screen
 
 
Q