使 UIButton 占屏幕大小的百分比
Making a UIButton a % of the screen size
我注意到某些按钮尺寸在 iPhone 5 模拟器上看起来不错,但在 iPhone 6 模拟器上看起来不太好,这是因为我在UIButtons 最终会在我的应用程序屏幕底部留下很多空白 space。
无论我在什么设备上模拟,我都希望有一个占屏幕大小 40% 的按钮。
关于如何使按钮大小保持在屏幕大小的 40%(无论设备如何)的任何想法?
您不能将限制设置为屏幕高度的 40%。但是,如果按钮始终有 20 像素的前导和尾随超级视图,您可以使用该宽度并设置纵横比高度。
另一种方法是使用 UIScreen.mainScreen().bounds.size.height * 0.4
作为按钮高度。
第三种方法是使用按钮的超级视图来设置高度。假设您的按钮是 UIViewController
视图的直接子视图:view.bounds.size.height * 0.4
.
可能还有很多其他方法可以做到这一点,但据我所知,其中 none 涉及将高度设置为实际百分比。
这个函数给你屏幕的边界
var bounds = UIScreen.mainScreen().bounds
然后你可以设置按钮宽度乘以0.4 x bounds.size.width
此致
- Ctrl 从按钮拖动到超级视图和 select 等宽
打开大小检查器编辑等宽约束并将乘数设置为 0.4。
你会看到这样的东西:
添加缺失的约束并更新帧。
Swift 4.2
在代码中它真的很简单:
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(button)
button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
button.widthAnchor.constraint(equalToConstant: 100).isActive = true
button.heightAnchor.constraint(equalToConstant: UIScreen.main.bounds.height * 0.4).isActive = true
}
或使用这个代替当前的高度锚点:
button.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.4).isActive = true
希望这个帮助:)
我注意到某些按钮尺寸在 iPhone 5 模拟器上看起来不错,但在 iPhone 6 模拟器上看起来不太好,这是因为我在UIButtons 最终会在我的应用程序屏幕底部留下很多空白 space。
无论我在什么设备上模拟,我都希望有一个占屏幕大小 40% 的按钮。
关于如何使按钮大小保持在屏幕大小的 40%(无论设备如何)的任何想法?
您不能将限制设置为屏幕高度的 40%。但是,如果按钮始终有 20 像素的前导和尾随超级视图,您可以使用该宽度并设置纵横比高度。
另一种方法是使用 UIScreen.mainScreen().bounds.size.height * 0.4
作为按钮高度。
第三种方法是使用按钮的超级视图来设置高度。假设您的按钮是 UIViewController
视图的直接子视图:view.bounds.size.height * 0.4
.
可能还有很多其他方法可以做到这一点,但据我所知,其中 none 涉及将高度设置为实际百分比。
这个函数给你屏幕的边界
var bounds = UIScreen.mainScreen().bounds
然后你可以设置按钮宽度乘以0.4 x bounds.size.width
此致
- Ctrl 从按钮拖动到超级视图和 select 等宽
打开大小检查器编辑等宽约束并将乘数设置为 0.4。 你会看到这样的东西:
添加缺失的约束并更新帧。
Swift 4.2
在代码中它真的很简单:
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(button)
button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
button.widthAnchor.constraint(equalToConstant: 100).isActive = true
button.heightAnchor.constraint(equalToConstant: UIScreen.main.bounds.height * 0.4).isActive = true
}
或使用这个代替当前的高度锚点:
button.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.4).isActive = true
希望这个帮助:)