我正在尝试根据运行按钮的设备调整按钮大小。 iPhone SE
比 iPhone 8
小,因此按钮没有完全显示。
我尝试使用以下代码根据屏幕大小调整按钮的大小,但没有显示任何变化。
roundedCornerDeliveryButton.layer.cornerRadius = 8
roundedCornerKitHomeButton.layer.cornerRadius = 8
widthMultiplier = Double(self.view.frame.size.width) / 69
heightMultiplier = Double(self.view.frame.size.height) / 321
roundedCornerDeliveryButton.frame.size.width = roundedCornerDeliveryButton.frame.width * CGFloat(widthMultiplier)
roundedCornerDeliveryButton.frame.size.height = roundedCornerDeliveryButton.frame.height * CGFloat(heightMultiplier)
roundedCornerKitHomeButton.frame.size.width = roundedCornerKitHomeButton.frame.width * CGFloat(widthMultiplier)
roundedCornerKitHomeButton.frame.size.height = roundedCornerKitHomeButton.frame.height * CGFloat(heightMultiplier)
roundedCornerDeliveryButton.frame.origin = CGPoint(x: roundedCornerDeliveryButton.frame.origin.x * CGFloat(widthMultiplier), y: roundedCornerDeliveryButton.frame.origin.y * CGFloat(heightMultiplier))
roundedCornerKitHomeButton.frame.origin = CGPoint(x: roundedCornerKitHomeButton.frame.origin.x * CGFloat(widthMultiplier), y: roundedCornerKitHomeButton.frame.origin.y * CGFloat(heightMultiplier))
我该怎么做?
最佳答案
有几种方法可以做到这一点,但这取决于您首先声明按钮的方式。
如果您的按钮是在 Storyboard 或 Xib 文件中声明的,您可能应该使用布局约束。
例如,如果你想要一个按钮占 1/3,你首先用 View Controller 的顶 View 定义一个“等宽”的布局约束,然后你编辑那个约束并将它的乘数更改为 1: 3
布局系统将发挥其魔力,确保约束得到遵守,并且按钮始终为屏幕宽度的 1/3。
您可以声明多个类似的约束以自动遵守不同的约束,例如确保您的按钮高度始终高于 36pt,宽度永远不会超过 400pt,等等。只需定义适当的优先级和约束。
以这种方式定义大小限制的优点是可以在 Xib 中进行检查,因为您可以快速更改设备类型和方向并确保一切正常,甚至在运行代码之前。
祝你好运!
关于ios - 根据屏幕大小调整按钮的宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51557563/