我们什么时候需要按钮在 Swift 中发送参数? [英] When do we need button to send argument in Swift?

查看:25
本文介绍了我们什么时候需要按钮在 Swift 中发送参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在 Xcode 中将按钮作为 @IBAction func 连接时,我们可以在 Arguments: Sender 或 None 之间进行选择.

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

我们什么时候选择 Sender,什么时候选择 None?

When do we choose Sender and when None?

推荐答案

好吧,如果 action 方法需要知道哪个按钮触发了它,或者可以利用按钮的任何属性,那么你需要传递 sender(按钮)到方法.

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.

一个人为的例子是,如果你有一个计算器,它有一个+"和一个-"按钮.他们都可以共享操作方法 performCalculation(sender: NSButton) 并且该方法可以使用 sender's 符号(这将是按钮的 title)执行正确的计算.

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.

另一方面,如果您有一个按钮,例如可以清除文本字段上的所有输入,那么您可以将此按钮连接到一个方法 clearInput() 上,该方法不需要有关于触发它的按钮的任何信息(事实上,这里没有参数可以更容易地在代码的其他地方重用这个方法并以编程方式触发清除文本字段).

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).

我希望这对您有意义.没有明确的规则afaik.我猜这主要是品味问题.

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

这篇关于我们什么时候需要按钮在 Swift 中发送参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆