[英]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.我想知道如何以编程方式创建一个具有取决于设备的动态高度的 UIButton。 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.设置高度时,我需要输入一个整数,但如果显示用于 iPhone 6,我希望它是 60px,如果是 iPhone 5,我希望它是 50px ......等等。
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.我知道如果我用 IB 创建按钮,使用约束,我可以使用百分比高度比例,但是因为我需要以编程方式创建按钮,所以我有点坚持。 Thanks in advance!
提前致谢!
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?检索设备类型的方法取自iOS:如何在Swift中确定iphone型号? .
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.