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

株式会社D2C IDAdvent Calendar 2022

Day 2

[SwiftUI] TextFieldのmodifierに@FocusStateのProperty Wrapperを渡す

Last updated at Posted at 2022-12-01

概要

TextFieldのmodifierを使用してキャンセルボタン付きのTextFieldを作る。
キャンセルボタンを押すとフォーカスを外してキーボードが閉じるようにする。

環境

Xcode 14.0.1
iOS 15.5以上

@FocusStateのProperty WrapperをModifierに渡す

TextField側では@FocusStateだがModifier側では@FocusState.Bindingをつける

@FocusState.Binding var isFocused: Bool

作成したModifier

import SwiftUI

struct CancelModifier: ViewModifier {
    @FocusState.Binding var isFocused: Bool
    @State private var showCancelButton: Bool = false

    func body(content: Content) -> some View {
        HStack {
            content
            
            if showCancelButton {
                Button {
                    isFocused = false
                } label: {
                    Text("キャンセル")
                        .foregroundColor(.primary)
                }
                .transition(.move(edge: .trailing))
            }
        }
        .onChange(of: isFocused) { isfocused in
            withAnimation {
                showCancelButton = isfocused
            }
        }
    }
}

使い方

struct ContentView: View {
    @State private var text: String = ""
    @FocusState private var isTextFieldFocused: Bool

    var body: some View {
        
        VStack {
            TextField("Placeholder", text: $text)
                .focused($isTextFieldFocused)
                .modifier(CancelModifier(isFocused: $isTextFieldFocused))
                .textFieldStyle(.roundedBorder)
                .autocapitalization(.none)
                .padding(.horizontal)
            
            Spacer()
        }
    }
}

キャンセルボタンに.transition(.move(edge: .trailing))を指定すると右から出てきて右からでていくトランジションをつけることができていい感じになります。

補足

プレビューではキーボードが出ないため? orフォーカスが正しくとれない?ため動作確認できませんでした。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?