【问题标题】:Swift creating UIButton programmatically with dynamic heightSwift 以编程方式创建具有动态高度的 UIButton
【发布时间】:2016-05-28 16:15:36
【问题描述】:

我想知道如何根据设备以编程方式创建具有动态高度的 UIButton。 假设我这样创建按钮:

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

在设置高度时,我需要输入一个整数,但如果显示适用于 iPhone 6,我希望它是 60px,如果是 iPhone 5,我希望它是 50px……等等。

如果我使用 IB 创建按钮,我知道该怎么做,使用约束并且我可以使用百分比高度比例,但由于我需要以编程方式创建按钮,所以我有点坚持。 提前致谢!

【问题讨论】:

  • 为什么不直接以编程方式添加高度约束?

标签: ios swift uibutton constraints


【解决方案1】:

这是一个你可以做的事情的例子:

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))

获取设备类型的方法取自iOS: How to determine iphone model in Swift?

【讨论】:

    猜你喜欢
    • 2018-02-18
    • 2019-08-06
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 2016-09-28
    • 1970-01-01
    • 2019-08-25
    相关资源
    最近更新 更多