1
2

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 1 year has passed since last update.

iOS強化月間 - iOSアプリ開発の知見を共有しよう -

【SwiftUI】カスタムのTextFieldStyleを作成する

Posted at

はじめに

LabelStyleやButtonStyleは使ったことがあったのですが、TextFieldStyleは使ったことがなかったので使ってみます。

Twitterの検索バー的なのを作ってみる

simulator_screenshot_A963A173-1BDD-4AF4-A4DB-F0480C762401.png

実装

struct WithCancelTextFieldStyle: TextFieldStyle {
    @FocusState private var isFocused
    
    func _body(configuration: TextField<Self._Label>) -> some View {
        HStack(spacing: 8) {
            HStack(spacing: 8) {
                Image(systemName: "magnifyingglass")
                
                configuration
            }
            .padding(.vertical, 10)
            .padding(.horizontal, 12)
            .background(.secondary.opacity(0.3), in: Capsule())
            
            Button {
                isFocused = false
            } label: {
                Text("Cancel")
            }
            .foregroundStyle(.primary)
        }
    }
}

extension TextFieldStyle where Self == WithCancelTextFieldStyle {
    static var withCancel: WithCancelTextFieldStyle {
        .init()
    }
}

使い方

struct SampleView: View {
    @State private var text = ""

    var body: some View {
        VStack {
            TextField("検索", text: $text)
                .textFieldStyle(.withCancel)
        }
        .padding(.horizontal, 16)
    }
}

おわり

body_がついてるのが気になります。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?