如何创建具有可变视图间距的UIStackView?

92

我有一个简单的水平UIStackView,其中包含几个UIView。我的目标是创建视图之间的可变间距。我知道可以使用“spacing”属性创建子视图之间的常量间距。然而,我的目标是创建可变间距。请注意,如果可能的话,我想避免使用作为间隔符的不可见视图。

最好的方法是将我的UIViews包装在单独的UIStackView中,并使用layoutMarginsRelativeArrangement = YES来尊重我的内部堆栈的布局边距。我希望能够对任何UIView执行类似的操作,而不必采用这种丑陋的解决方法。以下是我的示例代码:

// Create stack view
UIStackView *stackView = [[UIStackView alloc] init];
stackView.translatesAutoresizingMaskIntoConstraints = NO;
stackView.axis = UILayoutConstraintAxisHorizontal;
stackView.alignment = UIStackViewAlignmentCenter;
stackView.layoutMarginsRelativeArrangement = YES;

// Create subview
UIView *view1 = [[UIView alloc] init];
view1.translatesAutoresizingMaskIntoConstraints = NO;
// ... Add Auto Layout constraints for height / width
// ...
// I was hoping the layoutMargins would be respected, but they are not
view1.layoutMargins = UIEdgeInsetsMake(0, 25, 0, 0);

// ... Create more subviews
// UIView view2 = [[UIView alloc] init];
// ...

// Stack the subviews
[stackView addArrangedSubview:view1];
[stackView addArrangedSubview:view2];
结果是一个堆栈,其中的视图彼此靠近并带有间距:

在此输入图像描述

6个回答

177

iOS 11的更新:自定义间距的StackView

Apple在iOS 11中增加了设置自定义间距的功能。您只需在每个排列的子视图后指定间距即可。不幸的是,您不能指定前面的间距。

stackView.setCustomSpacing(10.0, after: firstLabel)
stackView.setCustomSpacing(10.0, after: secondLabel)

仍然比使用自己的视图好得多。

对于 iOS 10 及以下版本

您可以简单地将透明视图添加到堆栈视图中,并向它们添加宽度约束。

(标签 - 视图 - 标签 - 视图 - 标签)

如果您保持 distribution 为 fill,则可以在您的 UIView 上设置可变宽度约束。

但是,如果是这种情况,我会考虑是否使用堆栈视图是正确的选择。自动布局使得在视图之间设置可变宽度非常容易。


2
谢谢,但我希望不必使用空视图来添加空间或返回自动布局。虽然如果UIStackView不支持我的用例,我可能仍需要这样做。 - yura
2
你为什么想要间距是可变的?如果你使用“分布”和“等中心”,你可以有可变间距。这将使中心点等宽分开,但间距会变化。请更详细地解释你的用例。 - Rob Norback
2
基本上,我有几个视图需要水平(或垂直)分布,并且这些视图之间需要预定的空间,这些空间可能相等也可能不相等。我希望能够使用layoutMargins或其他机制来指定这些边距。 - yura
好的,我会做的!感谢您的帮助。为了澄清您的评论“我相信在stackview中设置UIView的约束是最直接的解决方案”,您是指您最初建议在可见视图之间插入空白视图吗? - yura
让我们在聊天中继续这个讨论 - Rob Norback
显示剩余4条评论

5

SWIFT 4

根据lilpit的答案,这里提供了一个UIStackView的扩展,可以为您的arrangedSubview添加顶部和底部间距。

extension UIStackView {
    func addCustomSpacing(top: CGFloat, bottom: CGFloat) {

        //If the stack view has just one arrangedView, we add a dummy one
        if self.arrangedSubviews.count == 1 {
            self.insertArrangedSubview(UIView(frame: .zero), at: 0)
        }

        //Getting the second last arrangedSubview and the current one
        let lastTwoArrangedSubviews = Array(self.arrangedSubviews.suffix(2))
        let arrSpacing: [CGFloat] = [top, bottom]

        //Looping through the two last arrangedSubview to add spacing in each of them
        for (index, anArrangedSubview) in lastTwoArrangedSubviews.enumerated() {

            //After iOS 11, the stackview has a native method
            if #available(iOS 11.0, *) {
                self.setCustomSpacing(arrSpacing[index], after: anArrangedSubview)
                //Before iOS 11 : Adding dummy separator UIViews
            } else {
                guard let arrangedSubviewIndex = arrangedSubviews.firstIndex(of: anArrangedSubview) else {
                    return
                }

                let separatorView = UIView(frame: .zero)
                separatorView.translatesAutoresizingMaskIntoConstraints = false

                //calculate spacing to keep a coherent spacing with the ios11 version
                let isBetweenExisitingViews = arrangedSubviewIndex != arrangedSubviews.count - 1
                let existingSpacing = isBetweenExisitingViews ? 2 * spacing : spacing
                let separatorSize = arrSpacing[index] - existingSpacing

                guard separatorSize > 0 else {
                    return
                }

                switch axis {
                case .horizontal:
                    separatorView.widthAnchor.constraint(equalToConstant: separatorSize).isActive = true
                case .vertical:
                    separatorView.heightAnchor.constraint(equalToConstant: separatorSize).isActive = true
                }

                insertArrangedSubview(separatorView, at: arrangedSubviewIndex + 1)
            }
        }
    }
}

那么您将会像这样使用它:
//Creating label to add to the UIStackview
let label = UILabel(frame: .zero)

//Adding label to the UIStackview
stackView.addArrangedSubview(label)

//Create margin on top and bottom of the UILabel
stackView.addCustomSpacing(top: 40, bottom: 100)

3

根据Rob的回答,我创建了一个UIStackView扩展程序,可能会有所帮助:

extension UIStackView {
  func addCustomSpacing(_ spacing: CGFloat, after arrangedSubview: UIView) {
    if #available(iOS 11.0, *) {
      self.setCustomSpacing(spacing, after: arrangedSubview)
    } else {
      let separatorView = UIView(frame: .zero)
      separatorView.translatesAutoresizingMaskIntoConstraints = false
      switch axis {
      case .horizontal:
        separatorView.widthAnchor.constraint(equalToConstant: spacing).isActive = true
      case .vertical:
        separatorView.heightAnchor.constraint(equalToConstant: spacing).isActive = true
      }
      if let index = self.arrangedSubviews.firstIndex(of: arrangedSubview) {
        insertArrangedSubview(separatorView, at: index + 1)
      }
    }
  }
}

您可以随意使用和修改它,例如如果您需要"separatorView"的引用,只需返回UIView即可:

  func addCustomSpacing(_ spacing: CGFloat, after arrangedSubview: UIView) -> UIView?

1
如果您的stackView已经定义了间距,则此方法将无法正常工作(在这种情况下,IOS 11版本将按预期工作,但IOS10版本将具有不同的间距(2 * defaultSpacing + spacing))。 - lilpit
如果您想要自定义间距,就不应该使用间距属性。此外,您需要使用 stackView.alignment = .fill - Enrique
我不理解你的回答。使用 setCustomSpacing 方法,可以在未使用该方法的索引处使用间距属性,因此我的回答是正确的。 - lilpit
1
你复制并粘贴了我的答案,并使用了相同的 setCustomSpacing。此外,你还更改了名称和位置等内容,以使其看起来像是不同的答案。 - Enrique

1
为了支持iOS 11.x及以下版本,我扩展了UIStackView,就像Enrique提到的一样,但我修改它以包括:
  • 在arrangedSubview前添加一个空格
  • 处理已经存在并只需要更新的空格情况
  • 删除添加的空格
extension UIStackView {

    func addSpacing(_ spacing: CGFloat, after arrangedSubview: UIView) {
        if #available(iOS 11.0, *) {
            setCustomSpacing(spacing, after: arrangedSubview)
        } else {

            let index = arrangedSubviews.firstIndex(of: arrangedSubview)

            if let index = index, arrangedSubviews.count > (index + 1), arrangedSubviews[index + 1].accessibilityIdentifier == "spacer" {

                arrangedSubviews[index + 1].updateConstraint(axis == .horizontal ? .width : .height, to: spacing)
            } else {
                let separatorView = UIView(frame: .zero)
                separatorView.accessibilityIdentifier = "spacer"
                separatorView.translatesAutoresizingMaskIntoConstraints = false

                switch axis {
                case .horizontal:
                    separatorView.widthAnchor.constraint(equalToConstant: spacing).isActive = true
                case .vertical:
                    separatorView.heightAnchor.constraint(equalToConstant: spacing).isActive = true
                @unknown default:
                    return
                }
                if let index = index {
                    insertArrangedSubview(separatorView, at: index + 1)
                }
            }
        }
    }

    func addSpacing(_ spacing: CGFloat, before arrangedSubview: UIView) {

        let index = arrangedSubviews.firstIndex(of: arrangedSubview)

        if let index = index, index > 0, arrangedSubviews[index - 1].accessibilityIdentifier == "spacer" {

            let previousSpacer = arrangedSubviews[index - 1]

            switch axis {
            case .horizontal:
                previousSpacer.updateConstraint(.width, to: spacing)
            case .vertical:
                previousSpacer.updateConstraint(.height, to: spacing)
            @unknown default: return // Incase NSLayoutConstraint.Axis is extended in future
            }
        } else {
            let separatorView = UIView(frame: .zero)
            separatorView.accessibilityIdentifier = "spacer"
            separatorView.translatesAutoresizingMaskIntoConstraints = false

            switch axis {
            case .horizontal:
                separatorView.widthAnchor.constraint(equalToConstant: spacing).isActive = true
            case .vertical:
                separatorView.heightAnchor.constraint(equalToConstant: spacing).isActive = true
            @unknown default:
                return
            }
            if let index = index {
                insertArrangedSubview(separatorView, at: max(index - 1, 0))
            }
        }

    }

    func removeSpacing(after arrangedSubview: UIView) {
        if #available(iOS 11.0, *) {
            setCustomSpacing(0, after: arrangedSubview)
        } else {
            if let index = arrangedSubviews.firstIndex(of: arrangedSubview), arrangedSubviews.count > (index + 1), arrangedSubviews[index + 1].accessibilityIdentifier == "spacer" {
                arrangedSubviews[index + 1].removeFromStack()
            }
        }
    }

    func removeSpacing(before arrangedSubview: UIView) {
        if let index = arrangedSubviews.firstIndex(of: arrangedSubview), index > 0, arrangedSubviews[index - 1].accessibilityIdentifier == "spacer" {
            arrangedSubviews[index - 1].removeFromStack()
        }
    }
}


extension UIView {
    func updateConstraint(_ attribute: NSLayoutConstraint.Attribute, to constant: CGFloat) {
        for constraint in constraints {
            if constraint.firstAttribute == attribute {
              constraint.constant = constant
            }
        }
    }

    func removeFromStack() {
        if let stack = superview as? UIStackView, stack.arrangedSubviews.contains(self) {
            stack.removeArrangedSubview(self)
            // Note: 1
            removeFromSuperview()
        }
    }
}

注意:1 - 根据文档:
为了防止在调用堆栈的removeArrangedSubview:方法后视图出现在屏幕上,请通过调用视图的removeFromSuperview()方法显式地从子视图数组中删除视图,或将视图的isHidden属性设置为true。

0
为了实现类似于CSS margin和padding的行为。
  1. 填充

    myStackView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: top, leading: left, bottom: bottom, trailing: right);

  2. 边距(创建一个包装视图并向其添加填充)

        wrapper = UIStackView();
        wrapper!.frame = viewToAdd.frame;
        wrapper!.frame.size.height = wrapper!.frame.size.height + marginTop + marginBottom;
        wrapper!.frame.size.width = wrapper!.frame.size.width + marginLeft + marginRight;
        (wrapper! as! UIStackView).axis = .horizontal;
        (wrapper! as! UIStackView).alignment = .fill
        (wrapper! as! UIStackView).spacing = 0
        (wrapper! as! UIStackView).distribution = .fill
        wrapper!.translatesAutoresizingMaskIntoConstraints = false
    
        (wrapper! as! UIStackView).isLayoutMarginsRelativeArrangement = true;
        (wrapper! as! UIStackView).insetsLayoutMarginsFromSafeArea = false;
        wrapper!.directionalLayoutMargins = NSDirectionalEdgeInsets(top: marginTop, leading: marginLeft, bottom: marginBottom, trailing: marginRight);wrapper.addArrangedSubview(viewToAdd);
    

0

如果您不知道之前的视图,可以创建自己的间距UIView,并将其作为排列子视图添加到堆栈视图中。

func spacing(value: CGFloat) -> UIView {
    let spacerView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
    spacerView.translatesAutoresizingMaskIntoConstraints = false
    spacerView.heightAnchor.constraint(equalToConstant: value).isActive = true
    return spacerView
}
stackView.addArrangedSubview(spacing(value: 16))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接