2
1

More than 1 year has passed since last update.

[SwiftUI] Labelをカスタマイズして、Alignmentとスペースを変える

Posted at

はじめに

こんにちは!
アプリ開発が好きで、Swiftの勉強をしている大学生です。
温かい目で見ていただけると幸いです。

解決したい問題

HStack内ImageTextを並べる際はLabelを使って表現すると、なんだかいい感じです👍

struct HogeView: View {
    var body: some View {
        // ① 🔺
        HStack {
            Image(systemName: "person")
                .resizable()
                .frame(width: 50, height: 50)
                .background(.red)
                .clipShape(Circle())

            Text("hoge")
                .font(.system(size: 24))
        }
        
        // ② ⭕️
        Label {
            Text("hoge")
                .font(.system(size: 24))
        } icon: {
            Image(systemName: "person")
                .resizable()
                .frame(width: 50, height: 50)
                .background(.red)
                .clipShape(Circl
        } 
    }
}

しかし、上記のようにLabelを使った書き方の時に、以下のような場合で不便に感じました。

  • Labeltitleクロージャー内でTextを二つを並べたい時にAligmentがずれてしまう
  • ImageTextの間隔をさらに広げたい時。

例: ☟

struct HogeView: View {
    var body: some View {
        Label {
            VStack {
                Text("テスト")
                    .font(.system(size: 24))
                Text("テスト")
                    .font(.system(size: 24))
            }
            
        } icon: {
            Image(systemName: "person")
                .resizable()
                .frame(width: 50, height: 50)
                .background(.red)
                .clipShape(Circle())
        }
    }
}

もちろんLabelを使わなければ解決できますが、どうせならLabelを利用したまま解決していきたいと思います。

解決方法

下記のコードを実装します。

struct MyLabelStyle: LabelStyle {
    func makeBody(configuration: Configuration) -> some View {
        HStack(alignment: .center, spacing: 30) {
            configuration.icon
            configuration.title
        }
    }
}

LabelStyleを準拠させたMyLabelStyleを作り、引数のconfigurationを必要に応じていじったり、HStackalignmentspacingを変えることによって自由にLabelを変えることができます!
今回はspacingalignmentを変えたいので、上記のようなコードを定義しました。
これを先ほどのコードで呼び出します


struct Test02View: View {
    var body: some View {
        Label {
            VStack {
                Text("テスト")
                    .font(.system(size: 24))
                Text("テスト")
                    .font(.system(size: 24))
            }
            
        } icon: {
            Image(systemName: "person")
                .resizable()
                .frame(width: 50, height: 50)
                .background(.red)
                .clipShape(Circle())
        }
        .labelStyle(MyLabelStyle()) // <- 追加
    }
}

下記のように期待通りの結果となります。

Labelだけでなく、様々なViewHogeHogeStyleが用意されてるので、色々できそうです!

終わりに

誰かの役に立つことができていれば幸いです。
間違い等がありましたらご指摘していただけると幸いです🙏

参考

2
1
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
2
1