Trying to find which text field is active ios

后端 未结 7 2347
Happy的楠姐
Happy的楠姐 2020-12-28 14:26

I am trying to find which textfield is active for when the I move the view when the keyboard rises. I am trying to set a property in my viewcontroller from the subview of a

7条回答
  •  悲&欢浪女
    2020-12-28 15:09

    I did an extension for this.

    public extension UIResponder {
    
        private struct Static {
            static weak var responder: UIResponder?
        }
    
        public static func currentFirst() -> UIResponder? {
            Static.responder = nil
            UIApplication.shared.sendAction(#selector(UIResponder._trap), to: nil, from: nil, for: nil)
            return Static.responder
        }
    
        @objc private func _trap() {
            Static.responder = self
        }
    }
    

    Use:

    if let activeTextField = UIResponder.currentFirst() as? UITextField {
        // ...
    }
    

提交回复
热议问题