Ruben Ruben - 6 months ago 8
Swift Question

Swift creating UIButton programmatically with dynamic height

I'm wondering how can I create a UIButton programmatically with a dynamic height depending of the device.
Let's say that I create the button like this:

bigButton = BigButton(frame: CGRect(x: 0, y: 0, width: self.view.frame.width , height: 60))


When setting the height, I need to put an integer, but I would like this to be 60px if display is for iPhone 6, 50px if iPhone 5... and so on.

I know how to do that if I create the button with IB, using the constraints and I could use a percentage height proportion, but since I need to create the button programmatically I'm kind of stuck with that.
Thanks in advance!

Answer

Here's an example of something you can do:

var dynamicHeight: CGFloat
switch UIDevice().type {
    case .iPhone4:
        dynamicHeight = 40
    case .iPhone5:
        dynamicHeight = 50
    case .iPhone5S:
        dynamicHeight = 50
    case .iPhone6:
        dynamicHeight = 60
    case .iPhone6plus:
        dynamicHeight = 70
    default:
        dynamicHeight = 40
}

bigButton = BigButton(frame: CGRect(x: 0, y: 0, width: self.view.frame.width , height: dynamicHeight))

The method of retrieving the device type was taken from iOS: How to determine iphone model in Swift?.

Comments