ios - 根据屏幕大小调整按钮的宽度和高度

标签 ios swift size

我正在尝试根据运行按钮的设备调整按钮大小。 iPhone SEiPhone 8 小,因此按钮没有完全显示。

iphone SE simulator buttons not fully showing

我尝试使用以下代码根据屏幕大小调整按钮的大小,但没有显示任何变化。

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

enter image description here

布局系统将发挥其魔力,确保约束得到遵守,并且按钮始终为屏幕宽度的 1/3。

您可以声明多个类似的约束以自动遵守不同的约束,例如确保您的按钮高度始终高于 36pt,宽度永远不会超过 400pt,等等。只需定义适当的优先级和约束。

以这种方式定义大小限制的优点是可以在 Xib 中进行检查,因为您可以快速更改设备类型和方向并确保一切正常,甚至在运行代码之前。

祝你好运!

关于ios - 根据屏幕大小调整按钮的宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51557563/

相关文章:

ios - 搜索栏故障

ios - 使用自定义 Cell 在 TableView 中的任何索引处插入一行

ios - 在 UIImageView 上绘制而不替换其原始图像 iOS

swift - 如何在swift中比较嵌套集合

swift - 将注释更改为引脚

SVN 转储大小 : is it possible to reduce it?

html - CSS Div 根据网络浏览器调整大小

iOS 为什么 requestEndDate 早于 requestStartDate?

ios - 有没有办法为 `if (iOSApplicationExtension)` 添加 `UIApplication.shared` 条件

c - 搜索指针会发生什么?