首页 > 解决方案 > ios - 根据屏幕大小调整按钮的宽度和高度

问题描述

我正在尝试根据运行它们的设备调整按钮大小。iPhone SE比较小,iPhone 8因此按钮没有完全出现。

iphone SE 模拟器按钮未完全显示

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

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))

我该怎么做?

标签: iosswiftsize

解决方案


有几种方法可以做到这一点,但这首先取决于您如何声明您的按钮。

如果您的按钮在 Storyboard 或 Xib 文件中声明,您可能应该使用布局约束。

例如,如果你想让一个按钮占据 1/3,你首先用“等宽”的视图控制器的顶视图定义一个布局约束,然后编辑该约束并将其乘数更改为 1:3

在此处输入图像描述

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

你可以声明几个这样的约束来自动尊重不同的约束,比如确保你的按钮高度总是高于 36pt,宽度永远不超过 400pt,等等。只需要定义适当的优先级和约束。

以这种方式定义您的大小约束具有在 Xib 中可检查的优势,因为您可以快速更改设备类型和方向,并确保在运行代码之前一切正常。

祝你好运!


推荐阅读