我注意到iPhone 5模拟器上的某些按钮尺寸看起来很棒,但在iPhone 6模拟器上看起来不太好,这是因为我放在UIButton上的高度或约束最终会在底部留下很多空白区域。我的应用程序屏幕
无论我在哪个设备上模拟,我都希望有一个40%的屏幕大小的按钮。
无论设备如何,关于如何使按钮大小的任何想法都保持在屏幕尺寸的40%?
您不能将约束设置为屏幕高度的40%。但是,如果按钮始终具有20px前导和尾随超视图,则可以使用该宽度并设置宽高比高度。
另一种方法是使用UIScreen.mainScreen().bounds.size.height * 0.4
作为您的按钮高度。
第三种方法是使用按钮的超视图来设置高度。假设您的按钮是UIViewController
视图的直接子项:view.bounds.size.height * 0.4
。
可能还有很多其他方法可以做到这一点,但据我所知,它们都不会涉及将高度设置为实际百分比。
此功能为您提供屏幕边界
var bounds = UIScreen.mainScreen().bounds
然后你可以设置按钮宽度乘以0.4 x bounds.size.width
问候
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
}
或使用此而不是当前的heightAnchor:
button.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.4).isActive = true
希望这个帮助:)