annidy / notes

1 stars 0 forks source link

UIStackView使用 #8

Open annidy opened 1 year ago

annidy commented 1 year ago

修改两个View的间距

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

https://stackoverflow.com/a/32999569/1118964

annidy commented 1 year ago

插入一个高度固定的分割线

let v:UIView = UIView()
v.heightAnchor.constraint(equalToConstant: 1).isActive = true
v.backgroundColor = .gray
stack.insertArrangedSubview(v, at: 3)
annidy commented 1 year ago

StackView没有默认的的删除所有子控件的API,只提供 removeArrangedSubviews + block,给到开发者自己决定如何处理。 一个常见的写法是 https://stackoverflow.com/a/46600798/1118964

extension UIStackView {

    func safelyRemoveArrangedSubviews() {

        // Remove all the arranged subviews and save them to an array
        let removedSubviews = arrangedSubviews.reduce([]) { (sum, next) -> [UIView] in
            self.removeArrangedSubview(next)
            return sum + [next]
        }

        // Deactive all constraints at once
        NSLayoutConstraint.deactivate(removedSubviews.flatMap({ $0.constraints }))

        // Remove the views from self
        removedSubviews.forEach({ $0.removeFromSuperview() })
    }
}

它会把所有的子view的约束全部deactivate。这就会导致一个副作用:里面用过的View再使用是,约束会失效。举例来说:里面有一个UILabel,虽然没有给他设置约束,但是它有contentSize。如果文字不改变,那么约束也是不会更新的。如果这个label被上面的代码remove后又重新addArrangeSubview,将会失去高度而不显示。