How to determine which textfield is active swift

前端 未结 7 1739
太阳男子
太阳男子 2020-12-06 04:01

I cant figure out which UITextField is currently active so i can clear its text if they hit cancel on a UIBarButtonItem. Here is my code. There is

7条回答
  •  渐次进展
    2020-12-06 04:59

    /// Finds the textField that is the first responder in a view hierarchy
    func findActiveTextField(in subviews: [UIView], textField: inout UITextField?) {
    
        guard textField == nil else { return }
    
        for view in subviews {
            if let tf = view as? UITextField, view.isFirstResponder {
                textField = tf
                break
            }
            else if !view.subviews.isEmpty {
                findActiveTextField(in: view.subviews, textField: &textField)
            }
        }
    }
    
    // Usage
    var aView: UIView = UIView()
    var activeField : UITextField?
    findActiveTextField(in: aView.subviews, textField: &activeField)
    

提交回复
热议问题