Qiitaに書いたやつ

SwiftUIとXcodeのPreviewでオートレイアウトをリアルタイムで確認しながら実装できて感動した

XcodeiOSAutoLayoutSwiftSwiftUI
2019年10月16日

先週くらいにXcode11に上げてようやく触り始めたのですが、感動してしまったので動画に撮りました。

preview.gif

なんかUIViewRepresentableを使えば、SwiftUIでUIKitのViewを使えますよね

struct AutoLayout: UIViewRepresentable {
    func updateUIView(_ view: AutoLayoutView, context: UIViewRepresentableContext<AutoLayout>) {}
    
    func makeUIView(context: UIViewRepresentableContext<AutoLayout>) -> AutoLayoutView {
        AutoLayoutView()
    }
}

もちろんPreviewにも表示されるわけです。

struct AutoLayout_Previews: PreviewProvider {
    static var previews: some View {
        AutoLayout()
            .previewLayout(.fixed(width: 414, height: 300))
    }
}

Twitterを見ているとベータ版を触られてる人たちがコードレイアウトで書いても良さそうとか言ってたので、 オートレイアウトを試してみようといじってました。 でAutoLayoutViewの内部でコードでオートレイアウトを指定してあげたんですが、なんかpreviewに即反映されたんですよ。

final class AutoLayoutView: UIView {
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private let label = UILabel()

    override init(frame: CGRect) {
        super.init(frame: frame)
        initializeConstraints()
    }

    func initializeConstraints() {
        // label.leftAnchor....
    }
}

もしやと思いオートレイアウトをコードで書く用の自作Extensionを追加していじってみると、これも反映されました。 それが冒頭のgifです。


勤務先の企業でSwiftUIをメインのアプリで使えるようになるには後2年程かかるのでまだまだオートレイアウトを使わなければいけないのですが、このPreview機能の恩恵は大きそうです。


ソースはこんな感じです。 メソッドチェーンの ExtensionはNSLayoutAnchorをラップしているだけです。

final class AutoLayoutView: UIView {
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        initializeView()
        initializeConstraints()
    }
    
    private let iconImageView = UIImageView()
    private let nameLabel = UILabel()

    func initializeView() {
        nameLabel.text = "abouch"
        nameLabel.backgroundColor = .green
        addSubview(nameLabel)

        iconImageView.backgroundColor = .red
        iconImageView.layer.cornerRadius = 20
        addSubview(iconImageView)
    }
    
    func initializeConstraints() {
        iconImageView.chura.layout
            .size(100)
            .left(24)
            .centerY(self)
        
        nameLabel.chura.layout
            .left(iconImageView.rightAnchor + 24)
            .top(iconImageView.topAnchor + 16)
            .right(-24)
            .height(60)
    }
}

同じタグの投稿

2020 churabou