When do we need button to send argument in Swift?

依然范特西╮ 提交于 2019-12-07 19:46:13

问题


When connecting a button in Xcode as @IBAction func, we can choose between Arguments: Sender or None.

When do we choose Sender and when None?


回答1:


Well, if the action method needs to know which button triggered it, or can make use of any of the button's properties, then you would need to pass the sender (the button) to the method.

A contrived example for this would be if you have a calculator, which has a '+' and a '-' button. They both could share the action method performCalculation(sender: NSButton) and the method could use the sender's symbol (this would be the button's title) to perform the correct calculation.

On the other hand, if you have a button, that will for example clear all input on a textfield, then you would wire this button up to a method clearInput() which would not need to have any information about the button that triggered it (in fact, having no argument here would make it easier to reuse this method elsewhere in your code and trigger clearing the textfield programmatically).

I hope this makes sense to you. There are no clear rules afaik. It's mostly a matter of taste I guess.



来源:https://stackoverflow.com/questions/29174015/when-do-we-need-button-to-send-argument-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!