ios 如何使用自动布局创建总宽度的百分比?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26373598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:12:22  来源:igfitidea点击:

How to create percentage of total width using autolayout?

iosxcodeautolayout

提问by Jeffrey Berthiaume

I need to create three dynamic columns, each with a fixed percentage of the total width. Not thirds, but different values. For example, the following illustration shows three columns: the first being 42% wide, the second being 25% wide, and the third being 33% wide.

我需要创建三个动态列,每个列都占总宽度的固定百分比。不是三分之一,而是不同的价值观。例如,下图显示了三列:第一列宽 42%,第二列宽 25%,第三列宽 33%。

For a 600 pixel across viewcontroller, that would be 252, 150, and 198 pixels respectively.

对于跨视图控制器的 600 像素,分别为 252、150 和 198 像素。

However, for any subsequent display sizes (i.e. iPhone 4 landscape (960 wide) or iPad 2 portrait (768 wide), I would like the relative percentages to be the same (not the pixel widths quoted above).

但是,对于任何后续的显示尺寸(即 iPhone 4 横向(960 宽)或 iPad 2 纵向(768 宽),我希望相对百分比相同(而不是上面引用的像素宽度)。

Is there a way to do this using Storyboards (i.e. without code)? I can do this easily in code, but my goal is to put as much of this display logic as possible into the Storyboard.

有没有办法使用故事板(即没有代码)来做到这一点?我可以在代码中轻松完成此操作,但我的目标是将尽可能多的显示逻辑放入 Storyboard。

enter image description here

在此处输入图片说明

回答by matt

If, as you say, you know how to do it in code, then you already know how to do it in the storyboard. It's exactly the same constraints, but you are creating them visually rather than in code.

如果,如你所说,你知道如何在代码中做到这一点,那么你已经知道如何在故事板中做到这一点。这是完全相同的约束,但您是在视觉上而不是在代码中创建它们。

  1. Select both a view and its superview.

  2. Choose Editor -> Pin -> Widths Equally to constrain the width to be equal to the superview's width (actually the "pin" popup dialog at the bottom of the canvas works best here).

  3. Edit the constraint and set the Multiplier to the desired fraction, e.g. 0.42. And so too for the other views.

  1. 选择一个视图及其超级视图。

  2. 选择 Editor -> Pin -> Widths Equally 将宽度限制为与超级视图的宽度相等(实际上画布底部的“pin”弹出对话框在这里效果最好)。

  3. 编辑约束并将乘数设置为所需的分数,例如 0.42。其他观点也是如此。

回答by Hyman

As Apple introduces UIStackViewit made job much easy.

当 Apple 引入UIStackView 时,它使工作变得容易得多。

Method 1: Using Nib/StoryBoard:

方法 1:使用笔尖/故事板:

You have to just add three view in interface builder & embed them into stackview

您只需在界面构建器中添加三个视图并将它们嵌入到堆栈视图中

Xcode ? Editor ? Embed in ? StackView

代码?编辑?嵌入 ? 堆栈视图

enter image description here

在此处输入图片说明

Select stackView & give constraint with leading, trailing, top & equal height with safeArea

选择 stackView 并使用安全区域给出前导、尾随、顶部和等高的约束

Click to Attribute inspector area & Set StackView horizontal & distribution to fill proportionally

单击属性检查器区域并 设置 StackView 水平和分布以按比例填充

[enter image description here3

[ 在此处输入图片说明3

Give constraint of three view with leading, trailing, top, bottom with respective of sides. enter image description here

给予前、后、顶、底三个视图的约束。 在此处输入图片说明

Method 2: Programmatically:

方法 2:以编程方式:

import UIKit
class StackViewProgramatically: UIViewController {
    var propotionalStackView: UIStackView!
    ///Initially defining three views
    let redView: UIView = {
        let view = UIView()//taking 42 % initially
        view.frame = CGRect(x: 0, y: 0, width: 42 * UIScreen.main.bounds.width/100, height: UIScreen.main.bounds.height)
        view.backgroundColor = .red
        return view
    }()

    let greenView: UIView = {
        let view = UIView()//taking 42* initially
        view.frame = CGRect(x: 42 * UIScreen.main.bounds.width/100, y: 0, width: 25 * UIScreen.main.bounds.width/100, height: UIScreen.main.bounds.height)
        view.backgroundColor = .green
        return view
    }()
    let blueView: UIView = {
        let view = UIView()//taking 33*initially
        view.frame = CGRect(x: 67 * UIScreen.main.bounds.width/100, y: 0, width: 33 * UIScreen.main.bounds.width/100, height: UIScreen.main.bounds.height)
        view.backgroundColor = .blue
        return view
    }()

    ///Changing UIView frame to supports landscape mode.
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        DispatchQueue.main.async {
            self.redView.frame = CGRect(x: 0, y: 0, width: 42 * self.widthPercent, height: self.screenHeight)
            self.greenView.frame = CGRect(x: 42 * self.widthPercent, y: 0, width: 25 * self.widthPercent, height: self.screenHeight)
            self.blueView.frame = CGRect(x: 67 * self.widthPercent, y: 0, width: 33 * self.widthPercent, height: self.screenHeight)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        //Adding subViews to the stackView
        propotionalStackView = UIStackView()
        propotionalStackView.addSubview(redView)
        propotionalStackView.addSubview(greenView)
        propotionalStackView.addSubview(blueView)
        propotionalStackView.spacing = 0
        ///setting up stackView
        propotionalStackView.axis = .horizontal
        propotionalStackView.distribution = .fillProportionally
        propotionalStackView.alignment = .fill
        view.addSubview(propotionalStackView)
    }
}
//MARK: UIscreen helper extension
extension NSObject {

    var widthPercent: CGFloat {
        return UIScreen.main.bounds.width/100
    }

    var screenHeight: CGFloat {
        return UIScreen.main.bounds.height
    }
}

Output:

输出:

Works with landscape & portrait

适用于横向和纵向

enter image description hereenter image description here

在此处输入图片说明在此处输入图片说明

Demo project - https://github.com/janeshsutharios/UIStackView-with-constraints

演示项目 - https://github.com/janeshsutharios/UIStackView-with-constraints

https://developer.apple.com/videos/play/wwdc2015/218/

https://developer.apple.com/videos/play/wwdc2015/218/

回答by JuJoDi

I think this can be explained in more detail so it can be more easily applied to any number of views requiring fixed percentage layouts within a superview.

我认为这可以更详细地解释,因此它可以更容易地应用于需要在超级视图中固定百分比布局的任意数量的视图。

Left-most view

最左边的视图

  • Anchored to SuperView.Leading
  • Defines its fixed percentage as a multiplier on the SuperView.Height
  • 锚定到 SuperView.Leading
  • 将其固定百分比定义为 SuperView.Height

Intermediate views

中间观点

  • Defines its fixed percentage as a multiplier on the SuperView.Height
  • Pins its leftto its neighbor's right
  • 将其固定百分比定义为 SuperView.Height
  • left把它钉在邻居的右边

Right-Most view

最右视图

  • Does not define a fixed percentage (it is the remainder of the available view)
  • Pins its leftto its neighbor's right
  • Pins its rightto SuperView.Trailing
  • 不定义固定百分比(它是可用视图的剩余部分)
  • left把它钉在邻居的右边
  • 将其固定rightSuperView.Trailing

All Views

所有视图

  • Define their non-fixed heights by anchoring to Top Layout Guide.Topand Top Layout Guide.bottom. In the answer above, it is noted that this can also be done by setting equal height to the neighboring view.
  • 通过锚定到Top Layout Guide.Top和来定义它们的非固定高度Top Layout Guide.bottom。在上面的答案中,注意到这也可以通过设置与相邻视图相等的高度来完成。