What's the difference between AnyObject and UIbutton as sender?

前端 未结 3 516
南笙
南笙 2020-12-29 09:48

When defining an IBAction, there\'s an option for Anyobject and UIButton, both works, what\'s the difference?

3条回答
  •  感情败类
    2020-12-29 10:16

    Yes, both works. The difference is just that by declaring it to a button, you get a typecasted reference as UIButton instead of AnyObject (or id in Objective-C). If you did not do that you will have to do it manually inside the code.

    You should prefer leaving it to AnyObject in case the action has some code you would like to call from anywhere else, rather than just the button action.

    For example a refresh button, you might have to do a refresh programatically. If you have set your action parameter to UIButton, you have to send an UIButton (but why??? You are doing it programatically, right?). Whereas if it is AnyObject, you can send 'self'. Which will also make you distinguish whether the refresh was done on action or programatically.

    Hope that explains. Sorry for no code. I am not into Swift coding much. Edits are welcome.

    EDIT

    So, even if it is AnyObject, it does have your UIButton properties. Just type cast it to use them.

提交回复
热议问题