You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI:如何用@FocusState实现输入达限自动隐藏/唤起键盘

Solution

To implement the required behavior using @FocusState and TextField.focused(), modify your PhoneNumberTextField component with the following changes:

  1. Add state variables to track focus state and previous phone number length
  2. Bind the TextField to the focus state
  3. 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 to TextField.focused($isFocused) lets us programmatically show/hide the keyboard.
  • Previous Length Tracking: The previousLength variable 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 11:10:42