【问题标题】:ios - Adjust button width and height based on screen sizeios - 根据屏幕大小调整按钮的宽度和高度
【发布时间】:2018-07-27 20:25:52
【问题描述】:

我正在尝试根据运行它们的设备调整按钮大小。 iPhone SEiPhone 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))

我该怎么做?

【问题讨论】:

    标签: ios swift size


    【解决方案1】:

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

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

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

    布局系统会施展魔法来确保遵守约束并且按钮始终是屏幕宽度的 1/3。

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

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

    祝你好运!

    【讨论】:

    • 太棒了!这就是我一直在寻找的
    【解决方案2】:

    要使按钮适合其内容,请使用

    button.sizeToFit()
    

    最好使用自动布局

    self.view.addSubview(button)
    button.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
       button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
       button.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
    ])
    

    如果需要,可以按比例添加此约束

    button.widthAnchor.constraint(equalTo:self.view.widthAnchor,multiplier:0.75)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      相关资源
      最近更新 更多