简体   繁体   English

删除 UIStackView 中的自定义间距

[英]Remove custom spacing in UIStackView

I have a stackview with three subviews:我有一个包含三个子视图的堆栈视图:

stackView.spacing = 8.0

stackView.addArrangeSubview(view1)
stackView.addArrangeSubview(view2)
stackView.addArrangeSubview(view3)

At some point, I add custom spacing after view2:在某些时候,我在 view2 之后添加了自定义间距:

stackView.setCustomSpacing(24.0, after: view2)

Now, I want to remove the custom spacing.现在,我想删除自定义间距。 Is this possible using UIStackView?这可以使用 UIStackView 吗? The only way I can think of is我能想到的唯一方法是

stackView.setCustomSpacing(8.0, after: view2)

but this will break if I ever change the spacing of my stackView to something other than 8.0, because spacing will remain 8.0 after view2.但是如果我将stackView的间距更改为8.0以外的其他值,这将中断,因为在view2之后间距将保持为8.0。

You should re-create stackView with specific spacing and replace the old one with the new stackView .您应该重新创建具有特定间距的stackView并用新的stackView替换旧的。

You can use a hack as an empty view with fixed height.您可以将 hack 用作具有固定高度的空视图。

let view1 = UIView(height: 50) // init with height is a custom convenience init
let view2 = UIView(height: 35)
let spacing = UIView(height: 20)
let stackView = UIStackView(arrangedSubviews: [view1, spacing, view2])
view.addSubview(stackView) // constraint if needed

在此处输入图像描述

let spacingView = UIView()

[View1, View2, spacingView, View3].forEach { view in 
  stackView.addArrangeSubview(view)
}

when you want to remove it just remove the spacingView from the array and you can play with width and height of the spacingView like you prefer当你想删除它时,只需从数组中删除spacingView ,你就可以像你喜欢的那样使用spacingView的宽度和高度

Try this extension:试试这个扩展:

extension UIStackView {

    // remove all custom spacing
    func removeCustomSpacing() -> Void {
        let a = arrangedSubviews
        arrangedSubviews.forEach {
            $0.removeFromSuperview()
        }
        a.forEach {
            addArrangedSubview($0)
        }
    }

    // remove custom spacing after only a single view
    func removeCustomSpacing(after arrangedSubview: UIView) -> Void {
        guard let idx = arrangedSubviews.firstIndex(of: arrangedSubview) else { return }
        removeArrangedSubview(arrangedSubview)
        insertArrangedSubview(arrangedSubview, at: idx)
    }
}

Use it simply as:简单地使用它:

myStackView.removeCustomSpacing()

or, if you are setting custom spacing on multiple views, and you want to remove it from only one view, use:或者,如果您在多个视图上设置自定义间距,并且只想从一个视图中删除它,请使用:

theStackView.removeCustomSpacing(after: view2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM