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

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

我有一个简单的水平

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];

结果是一个堆栈,视图彼此相邻且有间距:

swift autolayout ios9 uistackview
6个回答
177
投票

更新 iOS 11,具有自定义间距的 StackViews

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

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

仍然比使用自己的观点好得多。

适用于 iOS 10 及以下版本

您可以简单地将透明视图添加到堆栈视图中并为其添加宽度约束。

(标签 - UIView - 标签 - UIView - 标签)

并且如果您保留

distribution
来填充,那么您可以在 UIView 上设置可变宽度约束。

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


5
投票

斯威夫特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's 的回复中,我创建了一个 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
投票

为了支持 iOS 11.x 及更低版本,我像提到的 Enrique 一样扩展了 UIStackView,但是我将其修改为包括:

  • 在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边距和填充的行为。

  1. 填充

    myStackView.directionalLayoutMargins = NSDirectionalEdgeInsets(顶部:顶部, 前导:左,下:底部,尾随:右);

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

        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))
© www.soinside.com 2019 - 2024. All rights reserved.