Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjust button sizes based on screen size

I am making a home screen where I have 4-5 buttons. As we know that iphone 5/SE screen is smaller than iphone 6 and 7. Hence we need to expand and shrink the button size based on the screen size. What is the best approach or algorithm? I am using the fixed minimum sizes of the buttons to handle iphone 5 but these fixed smaller size buttons looks weird when we use iphone 6 and 7.

like image 898
Vajahat Ali Avatar asked Nov 07 '22 20:11

Vajahat Ali


2 Answers

There is an easy way to resize your buttons proportional to the screen size. Say for example that the correct button size is on the iPhone 5, which has a width of 320 and height of 568.

Declare two class variables (or global variables, if you want to resize buttons in different classes) called widthMultiplier and heightMultiplier:

var widthMultiplier = 0.0
var heightMultiplier = 0.0

In your viewDidLoad method, add the following code:

widthMultiplier = Double(self.view.frame.size.width) / 320
heightMultiplier = Double(self.view.frame.size.height) / 568

Then you can resize your buttons based on this:

button.frame.size.width = button.frame.width * CGFloat(widthMultiplier)
button.frame.size.height = button.frame.height * CGFloat(heightMultiplier)

And if you want, you can also adjust the position of that button to be proportional to the screen size so it shows up in the correct place on the iPhone 6/7 larger screen sizes such as the 6/7 Plus:

button.frame.origin = CGPoint(x: button.frame.origin.x * CGFloat(widthMultiplier), y: button.frame.origin.y * CGFloat(heightMultiplier))

I hope this helps.

like image 117
Rishi Pochiraju Avatar answered Nov 14 '22 21:11

Rishi Pochiraju


There's a couple of approaches that i have used to solve this problem:

Declare the sizes of the buttons in a model. The model should have a method that returns the size of the the button and then you can modify that value for each device/screen size. Example:

class MyLayoutClass {
    func getSizeForButton() -> CGSize {
        if UIDevice.current.userInterfaceIdiom == .pad {
            return CGSize(width: 100, height: 50)
        } else {
            // iphones
            let bounds = UIScreen.main.bounds
            // iphone SE has 320 width
            if bounds.width > 320 {
                return CGSize(width: 80, height: 50)
            } else {
                return CGSize(width: 50, height: 50) // smaller button size!
            }
        }
    }
}

You can then use this size to apply a screen-dependant size to your buttons

Another approach involves Interface Builder. You can set all your buttons to have a fixed margin to each other and then apply "Equal Widths" relationships to each other. See screenshot example:

enter image description here

like image 44
Juan Carlos Ospina Gonzalez Avatar answered Nov 14 '22 23:11

Juan Carlos Ospina Gonzalez