我注意到在iPhone 5模拟器上,某些按钮尺寸看起来很好,但在iPhone 6模拟器上并不理想,这是因为我放置在UIButtons上的高度或约束会留下很多空白空间在我的应用屏幕底部。
我希望有一个按钮的大小始终占据屏幕的40%,无论我使用的设备是什么。
您有任何关于如何使按钮的大小始终占据屏幕40%的设想吗?
我希望有一个按钮的大小始终占据屏幕的40%,无论我使用的设备是什么。
您有任何关于如何使按钮的大小始终占据屏幕40%的设想吗?
打开尺寸检查器,编辑“等宽度”约束,并将乘数设置为0.4。
然后您会看到类似于这样的内容:
添加缺少的约束并更新帧。
UIScreen.mainScreen().bounds.size.height * 0.4
作为按钮高度。第三种方法是使用按钮的父视图来设置高度。假设您的按钮是UIViewController
视图的直接子级:view.bounds.size.height * 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
}
或者使用这个代替当前的 heightAnchor:
button.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.4).isActive = true
这个函数可以给你屏幕的边界
var bounds = UIScreen.mainScreen().bounds
然后你可以通过将按钮宽度乘以0.4 x bounds.size.width来设置按钮的宽度
祝好