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

More than 3 years have passed since last update.

[SwiftUI] Qiitaのタグみたいに表示されるTextFieldを作る

Posted at

SwiftUIのTextFieldはカスタマイズ性に乏しいのですが、見かけだけでもそれっぽくしてみました。
ezgif-3-929af5259172.gif

実装

struct TestView: View {
    @State private var text: String = ""
    var body: some View {
        ZStack{
            TextField("入力", text: $text)
                .foregroundColor(.clear)
            HStack(spacing: 0){
                let strings = text.split(separator: " ", omittingEmptySubsequences: false)
                ForEach(strings.indices, id: \.self){i in
                    Text(strings[i])
                        .background(
                            Color(.sRGB, red: 0.847, green: 0.917, blue: 0.992)
                                .cornerRadius(5)
                                .overlay(
                                    RoundedRectangle(cornerRadius: 5)
                                        .stroke(Color(.sRGB, red: 0.745, green: 0.866, blue: 0.988))
                                )
                        )
                        .padding(.horizontal, 2)
                }
                Spacer()
            }
        }
    }
}

ポイント

TextFieldは制約が大きすぎるので色をclearにして見えなくし、その上から好きなように表示します。

制約

上からテキストを被せている都合上、カーソルが見えなくなります。これを防ぐためには例えばテキストの背景のカラーを透明色にすればいいのですが、色を合わせるのが大変だったので断念しました。

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