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

SwiftUI下iOS15以下版本如何检测SecureField是否处于光标聚焦状态

解决方案

你可以通过UIKit桥接的方式封装自定义安全输入框,完全满足版本适配和状态监听需求:

  • 封装遵循UIViewRepresentable协议的自定义安全输入框,开启isSecureTextEntry属性,同时通过UITextFieldDelegate的代理方法监听编辑状态变化
import SwiftUI

struct CustomSecureField: UIViewRepresentable {
    @Binding var text: String
    let placeholder: String
    // 对外暴露的编辑状态回调
    let onEditingChange: (Bool) -> Void
    
    func makeUIView(context: Context) -> UITextField {
        let textField = UITextField()
        textField.isSecureTextEntry = true
        textField.placeholder = placeholder
        textField.delegate = context.coordinator
        return textField
    }
    
    func updateUIView(_ uiView: UITextField, context: Context) {
        uiView.text = text
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    class Coordinator: NSObject, UITextFieldDelegate {
        let parent: CustomSecureField
        
        init(_ parent: CustomSecureField) {
            self.parent = parent
        }
        
        func textFieldDidBeginEditing(_ textField: UITextField) {
            parent.onEditingChange(true)
        }
        
        func textFieldDidEndEditing(_ textField: UITextField) {
            parent.onEditingChange(false)
        }
        
        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            if let currentText = textField.text as NSString? {
                parent.text = currentText.replacingCharacters(in: range, with: string)
            }
            return true
        }
    }
}
  • 业务代码中直接调用即可获取焦点状态,用法和原生SecureField保持一致
struct LoginView: View {
    @State private var password = ""
    @State private var isSecureFieldFocused = false
    
    var body: some View {
        CustomSecureField(text: $password, placeholder: "请输入密码") { isFocused in
            isSecureFieldFocused = isFocused
            // 按需处理焦点状态变化逻辑
        }
        .frame(height: 48)
        .padding(.horizontal, 16)
        .border(isSecureFieldFocused ? Color.blue : Color.gray, width: 1)
        .cornerRadius(4)
    }
}

该方案兼容iOS13及以上系统版本,覆盖所有触发输入框焦点的场景(点击、键盘切换、代码主动唤出等),完全符合你的限制要求。

内容的提问来源于stack exchange,提问作者Hamza Jadid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 01:18:04