Search code examples
iosswiftuiviewfirst-responder

Trying to loop through UIView and all subviews to get the first responder, not working


I am trying to find the current focused First Responder by looping through the main UIView and all of it's SubViews, and all of it's SubViews through recursion, but I am coming up with nil.

extension UIView {
func getCurrentFirstResponder() -> AnyObject? {
    if self.isFirstResponder() {
        return self
    }

    for subView: UIView in self.subviews as [UIView] {
        if subView.isFirstResponder() {
            return subView
        }
        else {
            subView.getCurrentFirstResponder()
        }
    }
    return nil
}
}

let focusedView = self.view.getCurrentFirstResponder() as? UIView

Does this look correct? Why am I getting a nil view when I use this?


Solution

  • Try this:

    for subView: UIView in self.subviews as [UIView] {
        if subView.isFirstResponder() {
            return subView
        }
        else {
            if let sub = subView.getCurrentFirstResponder() {
               return sub;
            }
        }
    }
    return nil