How to resign first responder from text field when user tap elsewhere?

前端 未结 18 3154
野趣味
野趣味 2020-12-14 02:12

I have filled my view with ScrollView (same size as the view) and I\'m stuck at how to resign first responder when user tap elsewhere in the View (or the scrollview). Any id

18条回答
  •  南笙
    南笙 (楼主)
    2020-12-14 02:35

    Nobody has yet presented the best answer here:

    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
    

    From the documentation on this method:

    Normally, this method is invoked by a UIControl object that the user has touched. The default implementation dispatches the action method to the given target object or, if no target is specified, to the first responder. Subclasses may override this method to perform special dispatching of action messages.

    I bolded the relevant part of that paragraph. By specifying nil for the to: parameter, we automatically call the given selector on the first responder, wherever it is, and we don't need to have any knowledge of where in the view hierarchy it is. This can also be used to invoke other methods on the first responder as well, not just cause it to resign first responder status.

提交回复
热议问题