0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SwiftUIでMaterialDesignライクなIconText作ってみた

Last updated at Posted at 2025-08-14

そもそもMaterial Designを使えばいいじゃんって話は置いておいて。。。

import SwiftUI
import SwiftUICore

struct IconText<LeadingImageContent, Content, TrailingImageContent>: View where LeadingImageContent: View, Content: View, TrailingImageContent: View {
    let backgroundColor: Color
    @ViewBuilder let leadingImage: () -> LeadingImageContent
    @ViewBuilder let content: () -> Content
    @ViewBuilder let trailingImage: () -> TrailingImageContent
    
    init(
        backgroundColor: Color,
        @ViewBuilder leadingImage: @escaping () -> LeadingImageContent = { EmptyView() },
        @ViewBuilder content: @escaping () -> Content,
        @ViewBuilder trailingImage: @escaping () -> TrailingImageContent = { EmptyView() }
    ) {
        self.backgroundColor = backgroundColor
        self.leadingImage = leadingImage
        self.content = content
        self.trailingImage = trailingImage
    }
    
    var body: some View {
        HStack {
            leadingImage().padding(5)
            
            content()
            
            trailingImage().padding(5)
        }
        .padding(.horizontal, 10)
        .padding(.vertical, 5)
        .background(
            RoundedRectangle(cornerRadius: 10)
                .fill(backgroundColor)
        )
        .padding(2)
    }
}

使い方はこんな感じ

#Preview {
    VStack {
        IconText(
            backgroundColor: .blue,
            content: {
                Text("アイコンなし")
            }
        )
        
        IconText(
            backgroundColor: .blue,
            leadingImage: {
                Image(systemName: "paperplane")
            },
            content: {
                Text("前アイコンのみ")
            }
        )
        
        IconText(
            backgroundColor: .blue,
            content: {
                Text("後ろアイコンのみ")
            },
            trailingImage: {
                Image(systemName: "paperplane")
            }
        )
        
        IconText(
            backgroundColor: .blue,
            leadingImage: {
                Image(systemName: "paperplane")
            },
            content: {
                Text("両アイコンあり")
            },
            trailingImage: {
                Image(systemName: "paperplane")
            }
        )
    }
}

見た目はこんな感じ

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?