A Small Improvement To UIView and UIStackView
I write a lot of UI code in UIKit, and in particular in code rather than using Interface Builder.
Quite often I'll want to add multiple subviews to a UIView
, or multiple arranged subviews to a UIStackView
. And I end up with code like this:
view.addSubview(subview1)
view.addSubview(subview2)
view.addSubview(subview3)
stackView.addArrangedSubview(subview1)
stackView.addArrangedSubview(subview2)
stackView.addArrangedSubview(subview3)
stackView.addArrangedSubview(subview4)
stackView.addArrangedSubview(subview5)
Which isn't amazing to read. It's a lot of duplication, and makes it slower to create new views. I almost always end up writing these extensions:
extension UIView {
func addSubviews(_ subviews: [UIView]) {
for view in subviews {
addSubview(view)
}
}
func addSubviews(_ subviews: UIView...) {
for view in subviews {
addSubview(view)
}
}
}
extension UIStackView {
func addArrangedSubviews(_ subviews: [UIView]) {
for view in subviews {
addArrangedSubview(view)
}
}
func addArrangedSubviews(_ subviews: UIView...) {
for view in subviews {
addArrangedSubview(view)
}
}
}
I create both versions because sometimes you can have an array of subviews to add, so it's nice to be able to just call view.addSubviews(myArrayOfViews)
. But usually I have a scenario like the one above, so I can use the variadic function and replace the 8 lines of code with these 2:
view.addSubviews(subview1, subview2, subview3)
stackView.addArrangedSubviews(subview1, subview2, subview3, subview4, subview5)
Published on 11 January 2022