SwiftUI:如何用@FocusState实现输入达限自动隐藏/唤起键盘
Solution
To implement the required behavior using @FocusState and TextField.focused(), modify your PhoneNumberTextField component with the following changes:
- Add state variables to track focus state and previous phone number length
- Bind the TextField to the focus state
- Implement focus logic based on phone number length changes
Here's the updated PhoneNumberTextField.swift code:
struct PhoneNumberTextField: View { @Binding var phoneNumber: String @Binding var isTypingFinished: Bool @Binding var isError: Bool // Track TextField focus state @FocusState private var isFocused: Bool // Track previous length to detect deletion from 11 digits @State private var previousLength: Int = 0 private var borderColor: Color { return isError ? Colors.error : .white } var body: some View { HStack(spacing: 15) { TextField( "মোবাইল নম্বর দিন", text: $phoneNumber ) .onReceive(Just(phoneNumber)) { text in // Filter non-numeric characters and limit to 11 digits let numericText = text.filter { "0123456789".contains($0) } let limitedText = numericText.limitTo(limit: 11) // Avoid redundant updates if phoneNumber != limitedText { phoneNumber = limitedText } let currentLength = phoneNumber.count // Update typing completion state isTypingFinished = currentLength == 11 // Handle keyboard focus if currentLength == 11 { // Dismiss keyboard when reaching 11 digits isFocused = false } else if previousLength == 11 && currentLength < 11 { // Reactivate keyboard when deleting from full length isFocused = true } // Update previous length for next cycle previousLength = currentLength } // Bind TextField to focus state variable .focused($isFocused) .keyboardType(.decimalPad) .font(.custom(Fonts.Balooda2_Regular, size: 15)) } .padding(20) .background(Rectangle().fill(.white)) .overlay( Rectangle() .strokeBorder(borderColor, style: StrokeStyle(lineWidth: 1.0)) ) } }
Key Details:
@FocusState: This property wrapper controls the TextField's focus state. Binding it toTextField.focused($isFocused)lets us programmatically show/hide the keyboard.- Previous Length Tracking: The
previousLengthvariable detects when the user deletes characters from a full 11-digit number, triggering the keyboard to reappear. - Text Processing: Combined filtering and limiting steps to avoid redundant updates and potential infinite loops.
No changes are needed in PhoneNumberView.swift or AuthenticationViewModel.swift—all focus logic is encapsulated within the PhoneNumberTextField component.
内容的提问来源于stack exchange,提问作者Aminul Haque Aome
相关产品推荐
相关产品推荐

