I am passing FocusState property(focusField) from (TextFieldObservers) view to customTextFieldView through binding.
Aim: on tapping on the TextFieldObservers View, the keyboard should dismiss?
Problem: On taping the textfield in TextFieldObservers View, keyboard also dismissing. Which is not required?
below is my code.
import SwiftUI
import Foundation
enum Placeholder: Hashable {
case email
case password
var description: String {
switch self {
case .email: return "email"
case .password: return "password"
}
}
func nextControl() -> Placeholder {
return switch self {
case .email: .password
case .password: .email
}
}
}
struct TextFieldObservers: View {
@FocusState var focusedField: Placeholder?
@State var flag: Bool = false
var body: some View {
VStack {
VStack {
CustomTextField(placeHolder: .email,
description: "",
focusedField: $focusedField)
CustomTextField(placeHolder: .password,
description: "", focusedField: $focusedField)
}
.background(Color.green)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.red)
.onTapGesture {
focusedField = nil
}
}
}
struct CustomTextField: View {
var placeHolder: Placeholder
@State var description: String
@FocusState.Binding var focusedField: Placeholder?
init(placeHolder: Placeholder,
description: String,
focusedField: FocusState<Placeholder?>.Binding) {
self.placeHolder = placeHolder
self.description = description
self._focusedField = focusedField
}
var body: some View {
TextField(placeHolder.description, text: $description)
.padding(.horizontal, 20)
.frame(width: 300, height: 50)
.background {
RoundedRectangle(cornerRadius: 12)
.fill(.white)
}
.focused($focusedField, equals: placeHolder)
.submitLabel(.next)
.onSubmit {
focusedField = placeHolder.nextControl()
}
}
}
#Preview {
TextFieldObservers()
}
KeyBoard should persist on clicking the textfield and disappear clicking anywhere in the View.