Horizo ntal UIStackView-修复中心项目的大小并拉伸其他项目

问题描述 投票:0回答:2

我正在尝试实现这样的布局:

enter image description here

本质上,我需要or标签停留在中间并占据固定的宽度,并且线条需要朝屏幕边缘延伸。

这是我在XIB中所做的:

  • 创建了一个水平的UIStackview,对齐了center
  • 将堆栈视图的高度限制设置为20,分配为fill
  • 添加了两个UIView元素(用于灰线),并将高度限制设置为5。
  • 在上面的两个UIView元素之间添加了UILabel。
  • 添加了更多限制:
  • [左UIView从超级视图以0开头,并以5到中间标签尾迹
  • 右UIView从中间标签开始以4开头,并以0跟随到超级视图。

在“界面”构建器上看起来不错,但是在不同的屏幕尺寸和横向上,我发现中间的“ or”标签可以拉伸并踢掉左右UIViews来弥补可用空间,这似乎是正确的:enter image description here

如果在中间标签上设置20的宽度约束,则右侧的UIView会像这样不均匀地拉伸:

enter image description here

我知道元素的CHP在某种程度上很重要,我什至尝试设置像这样的CHP:

  • 中间标签的CHP为251

  • 左右UIViews的CHP为250。

这仍然使我无法正确展开UIView。

我做错了什么事?见解非常感谢!非常感谢!

ios uiview xib uistackview
2个回答
0
投票

未设置任何前导或尾随约束...

将“右视图”宽度约束设置为等于“左视图”宽度,并为您的堆栈视图提供spacing值为4或5。

故事板:

enter image description here

纵向:

enter image description here

横向:

enter image description here


0
投票

您需要在UIStackView上设置widthConstraint,并设置leftView.widthAnchor = rightView.widthAnchor。或者,您可以在UIStackView上设置前导和尾随约束,然后设置leftView.widthAnchor = rightView.widthAnchor。

下面是您可以在Playgrounds中试用的示例代码

    let leftView = UIView()
    leftView.translatesAutoresizingMaskIntoConstraints = false
    leftView.backgroundColor = .lightGray

    let rightView = UIView()
    rightView.translatesAutoresizingMaskIntoConstraints = false
    rightView.backgroundColor = .lightGray

    let orLabel = UILabel()
    orLabel.translatesAutoresizingMaskIntoConstraints = false
    orLabel.textColor = .black
    orLabel.text = "or"

    let stackView = UIStackView(arrangedSubviews: [leftView, orLabel,  rightView])
    stackView.alignment = .center
    stackView.distribution = .fill
    stackView.axis = .horizontal
    stackView.spacing = 5
    stackView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(stackView)

    stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    stackView.heightAnchor.constraint(equalToConstant: 20).isActive = true
    stackView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true

    leftView.heightAnchor.constraint(equalToConstant: 5).isActive = true
    rightView.heightAnchor.constraint(equalToConstant: 5).isActive = true
    leftView.widthAnchor.constraint(equalTo: rightView.widthAnchor).isActive = true
© www.soinside.com 2019 - 2024. All rights reserved.