SwiftUI Keyboard Dismiss
μ΄μ ꡬνν ν κ³Όμ λ₯Ό λ€μ ν λ² κ΅¬ννλ λμ€μ μΆκ°ν΄λ³΄κ³ μΆμ κΈ°λ₯μ΄ μμλ€.
μ¬μ©μ μ λ ₯μ μννΈ ν€λ³΄λ νΉμ λ²νΌμ ν΅ν΄μ μ λ ₯ λ°λλ°, μννΈ ν€λ³΄λλ‘ μ λ ₯ λ°μ κ²½μ°μ Submitμ λλ₯΄μ§ μκ³ , λ·°μ ν΄λ¦νλλΌλ μννΈ ν€λ³΄λκ° λ«νλλ‘ κ΅¬ννκ³ μΆμλ€.
1. Focused
μ°μ μ΄ κΈ°λ₯μ SwiftUI 3.0 (iOS 15) μ΄μλΆν° μ§μνλ€. κ·Έλ° νμΈκ° μ λ§ κ°λ¨νκ² κ΅¬νμ΄ κ°λ₯νλ€.
var body: some View {
@State private var input: String = ""
@FocusState private var isFocused: Bool
// μλ΅...
VStack {
TextField("PlaceHolder", $input)
.font(.title)
.focused(isFocused)
}
.onTapGesture {
isFocused = false
}
}
νμ§λ§ μ€μ λ‘ μ¬μ©ν λλ μ΄λ κ² λ¨μΌ λ·°μμ νμ©νμ§ μλλ€. μ¬λ¬ λ·°λ€μ΄ κ³μΈ΅ ꡬ쑰λ₯Ό μ΄λ£¨λ©΄μ λ°°μΉλμ΄ μμ κ²μ΄λ€.
μν νλ‘νΌν°λ μ μΈλ λ·°μμλ§ μ κ·Ό κ°λ₯νλ―λ‘ μμ λ·°μμ μ κ·ΌνκΈ° μν΄μ @Bindingμ μ¬μ©ν΄μΌ νλ€.
struct ParentView: View {
@FocusState private var isFocused: Bool
var body: some View {
VStack {
// μλ΅
ChildView(isFocused: self.$isFocused) // Bindingμ΄λ―λ‘ $
}
.onTapGesture {
isFocused = false
}
}
}
struct ChildView: View {
@State private var input: String = ""
@Binding var isFocused: Bool
var body: some View {
VStack {
// μλ΅
TextField("PlaceHolder", $input)
.focused(isFocused)
}
}
}
μμ λ·°λ @Bindingμ ν΅ν΄ λΆλͺ¨ λ·°μ μλ μν νλ‘νΌν°μ μ κ·Όνκ³ μλ€.
VStackμ ν°μΉνλ©΄ TextFieldμ Focusκ° falseλ‘ λ°λλ©΄μ μννΈ ν€λ³΄λλ λ΄λ €κ°κ² λ κ²μ΄λ€.
νμ§λ§ μ΄ μ½λλ μ»΄νμΌ μλ¬κ° λ°μνλ€.
보μνλ νμ μ λ¬Έμ μΈ κ² κ°λ€. νμ μ FocusState<Bool>.Binding μΌλ‘ μ€μ ν΄μ£Όλ©΄ μ»΄νμΌμ΄ μ μμ μΌλ‘ μ§νλλ€.
struct ParentView: View {
@FocusState private var isFocused: Bool
var body: some View {
VStack {
// μλ΅
ChildView(isFocused: isFocused) // Bindingμ΄λ―λ‘ $
}
.onTapGesture {
isFocused = false
}
}
}
struct ChildView: View {
@State private var input: String = ""
// @Binding -> FocusState<Bool>.Binding
var isFocused: FocusState<Bool>.Binding
var body: some View {
VStack {
// μλ΅
TextField("PlaceHolder", $input)
.focused(isFocused)
}
}
}