UIView Extension Finds First Responder in Subviews

This post may be out of date, you should verify the content before use

Often times when you have some kind of a "Done" button in your view controller, you'll have logic where you want to resign the first responder. There are a few different approaches to this, such as (for a UITextField) using the UITextFieldDelegate textFieldShouldBeginEditing(UITextField) function to keep track of the current first responder in a global variable, then sending a resignFirstResponder() message to that variable.

An easier approach which doesn't involve any bookkeeping for tracking the first responder is this UIView extension which will traverse all of the subviews (and their subviews) in a given UIView, looking for the first responder and optionally resigning it.

To use it, you just call myView.findFirstResponder() or myView.findAndResignFirstResponder(), to either find and return the first responder, or find and resign the first responder, respectively.

You can find the code for my extension on Github