Get the current first responder without using a private API

前端 未结 28 1793
夕颜
夕颜 2020-11-22 05:03

I submitted my app a little over a week ago and got the dreaded rejection email today. It tells me that my app cannot be accepted because I\'m using a non-public API; specif

28条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 05:55

    The first responder can be any instance of the class UIResponder, so there are other classes that might be the first responder despite the UIViews. For example UIViewController might also be the first responder.

    In this gist you will find a recursive way to get the first responder by looping through the hierarchy of controllers starting from the rootViewController of the application's windows.

    You can retrieve then the first responder by doing

    - (void)foo
    {
        // Get the first responder
        id firstResponder = [UIResponder firstResponder];
    
        // Do whatever you want
        [firstResponder resignFirstResponder];      
    }
    

    However, if the first responder is not a subclass of UIView or UIViewController, this approach will fail.

    To fix this problem we can do a different approach by creating a category on UIResponder and perform some magic swizzeling to be able to build an array of all living instances of this class. Then, to get the first responder we can simple iterate and ask each object if -isFirstResponder.

    This approach can be found implemented in this other gist.

    Hope it helps.

提交回复
热议问题