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

前端 未结 3 504
南笙
南笙 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 09:51

    If you are only ever going to use the function with a UIButton it is best practice to declare your sender as a UIButton. This saves you a bit of code and it also tells anyone in the future reading your code that you only expect the function to be used with a UIButton.

    Using AnyObject or Any will work, but you will need to do an guard let button = sender as? UIButton { return } in order to access it as a button. This way allows you to react differently depending on what the sender actually is, but I don't recommend doing that.

    0 讨论(0)
  • 2020-12-29 10:09

    If it's anyObject, then it doesn't have any of UIButton's properties. When you click the button and the IBAction fires, sender contains information about the thing that triggered the action.

    For example, for a UIButton, you might want to query the UIButton's text when the IBAction triggers.

    However, in a situation where the IBAction is connected to two different UI controls, let's say, a button and a slider, querying the sender when it's of type UIButton (while the triggering UI element is the UISlider) will crash the program. If you have AnyObject, you'll be able to test if the sender is a UIButton or a UISlider, and then do something.

    In general, if you don't care about sender, leave it blank, so people reading your code will know that you aren't using sender for anything.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题