【问题标题】:Making a UIButton a % of the screen size使 UIButton 占屏幕大小的百分比
【发布时间】:2015-06-25 07:29:33
【问题描述】:

我注意到某些按钮尺寸在 iPhone 5 模拟器上看起来很棒,但在 iPhone 6 模拟器上看起来不那么好,这是因为我放置在 UIButtons 上的高度或约束最终会留下很多空白空间我的应用屏幕底部。

无论我在什么设备上模拟,我都希望有一个屏幕大小为 40% 的按钮。

关于如何使按钮的大小保持在屏幕大小的 40% 而不考虑设备的任何想法?

【问题讨论】:

  • 有一个称为纵横比约束的约束,如果您按 Ctrl 单击 UI 按钮并拖动到同一个 UI 按钮,则会出现该约束。此约束使您的 UIbutton 在所有设备中保持相同的比例。

标签: swift uibutton constraints


【解决方案1】:
  1. Ctrl 从按钮拖动到 superview 并选择 Equal Widths
  2. 打开大小检查器编辑等宽约束并将乘数设置为 0.4。 你会看到这样的东西:

  3. 添加缺失的约束并更新帧。

【讨论】:

    【解决方案2】:

    您不能将约束设置为屏幕高度的 40%。但是,如果按钮始终有 20px 的前导和后缀到超级视图,您可以使用该宽度并设置纵横比高度。

    另一种方法是使用UIScreen.mainScreen().bounds.size.height * 0.4 作为按钮高度。

    第三种方法是使用按钮的超级视图来设置高度。假设您的按钮是 UIViewController 视图的直接子级:view.bounds.size.height * 0.4。

    可能还有很多其他方法可以做到这一点,但据我所知,它们都不会涉及将高度设置为实际百分比。

    【讨论】:

      【解决方案3】:

      这个函数给你屏幕的边界

      var bounds = UIScreen.mainScreen().bounds

      然后你可以设置按钮宽度乘以 0.4 x bounds.size.width

      问候

      【讨论】:

        【解决方案4】:

        斯威夫特 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
        

        希望对您有所帮助:)

        
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-03-29
          • 1970-01-01
          • 2012-08-31
          • 1970-01-01
          • 2023-03-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多