问题
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