LoginSignup
3
2

More than 1 year has passed since last update.

UIStackViewをViewBuilderで初期化できるVStackViewとHStackViewを作る

Posted at
let stackView = VStackView {
  UserProfileView(imageURL)
  UserNameView(name)
}

UIStackViewを便利に使うために、ViewBuilderを作って初期化できるようにしてみます。

import UIKit

@resultBuilder
public struct ArrangedSubviewBuilder {
    public static func buildBlock(_ components: UIView...) -> [UIView] {
        components
    }
}

public class HStackView: UIStackView {
    public convenience init(
        spacing: CGFloat = UIStackView.spacingUseSystem,
        @ArrangedSubviewBuilder arrangedSubviews: () -> [UIView]
    ) {
        self.init(frame: .null)
        self.spacing = spacing
        
        self.axis = .horizontal
        for view in arrangedSubviews() {
            addArrangedSubview(view)
        }
    }
}

public class VStackView: UIStackView {
    public convenience init(
        spacing: CGFloat = UIStackView.spacingUseSystem,
        @ArrangedSubviewBuilder arrangedSubviews: () -> [UIView]
    ) {
        self.init(frame: .null)
        self.spacing = spacing
        
        self.axis = .vertical
        for view in arrangedSubviews() {
            addArrangedSubview(view)
        }
    }
}
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2