swift 闭包作为属性_在Swift中将闭包作为目标添加到UIButton和其他控件

swift 闭包作为属性

The target-action pattern is used in combination with user interface controls as a callback to a user event. Whenever a button is pressed on a target, its action will be called. The fact that the method is not defined close to the control definition is sometimes seen as a downside and reason for a lot of us developers to search for closure-based solutions on sites like Stack Overflow.

目标操作模式与用户界面控件结合使用,作为对用户事件的回调。 只要在目标上按下按钮,就会调用其动作。 未将方法定义为与控件定义接近的事实有时被视为不利因素,也是许多美国开发人员在诸如Stack Overflow之类的站点上搜索基于闭包的解决方案的原因。

The iOS 14 SDK introduced new APIs that allow us to use UIControls in combination with closures. Common UIControl elements are UIButton, UISegmentedControl, and UISwitch, but there are a lot more that all inherit from the UIControl object. All those interface elements can now be used with this new API.

iOS 14 SDK引入了新的API,使我们可以将UIControls与闭包结合使用。 常见的UIControl元素是UIButtonUISegmentedControlUISwitch ,但是还有很多要继承自UIControl对象的元素。 现在,所有这些接口元素都可以与此新API一起使用。

使用带有闭包回调的UIControl (Using a UIControl With a Closure Callback)

You’re most likely familiar with the following piece of code:

您很可能熟悉以下代码:

final class ViewController: UIViewController {


    override func viewDidLoad() {
        super.viewDidLoad()


        let button = UIButton(type: .system)
        button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)


    }


    @IBAction func buttonTapped(_ sender: UIButton) {
        print("Button tapped!")
    }
}

The buttonTapped(_:) method will be called every time the button is tapped.

每次点击按钮时都会调用buttonTapped(_:)方法。

The same piece of code can now be written as follows:

现在可以按以下方式编写同一段代码:

final class ViewController: UIViewController {


    override func viewDidLoad() {
        super.viewDidLoad()


        let button = UIButton(type: .system, primaryAction: UIAction(title: "Button Title", handler: { _ in
            print("Button tapped!")
        }))
    }
}

This keeps the action close to the control definition, which can improve the discoverability of your code.

这样可以使操作接近控件定义,从而可以提高代码的可发现性。

获取对控制发送者的引用 (Getting a reference to the control sender)

One difference in the piece of code above is that our method had a reference to the sender. This could be handy in some cases when you want to know which of the controls in place called the linked method.

上面这段代码的不同之处在于我们的方法引用了发送者。 在某些情况下,当您想知道哪些控件称为链接方法时,这可能很方便。

With the new closure-based API, you can use the action argument to access the sender. For example, when you want to read out the text from a text field:

使用新的基于闭包的API,您可以使用action参数访问发送者。 例如,当您想从文本字段中读取文本时:

let textField = UITextField()
textField.addAction(UIAction(title: "", handler: { action in
let textField = action.sender as! UITextField
print("Text is \(textField.text)")
}), for: .editingChanged)

我应该始终使用新的Closure API吗? (Should I Always Use the New Closure API?)

It might be tempting to now use closures everywhere. However, a control action can easily grow in code, making your code less readable. In those cases, you might want to fall back to the old target-action pattern that allows you to use a separate method.

现在在所有地方都使用闭包可能很诱人。 但是,控制动作很容易在代码中增长,从而使代码的可读性降低。 在这些情况下,您可能希望退回到允许您使用单独方法的旧目标操作模式。

Methods in Swift are easier to read when your control action requires multiple lines of code.

当您的控制动作需要多行代码时,Swift中的方法更易于阅读。

结论 (Conclusion)

The new closure-based API in the iOS 14 SDK is a welcome change, but it should be used carefully. Using many closures can easily make your code less readable and should only be used if the control callback logic can be written in a few lines of code. Otherwise, it’s better to use the old-fashioned target-action pattern.

iOS 14 SDK中新的基于闭包的API是值得欢迎的更改,但应谨慎使用。 使用许多闭包可以很容易地使您的代码可读性降低,并且仅当控制回调逻辑可以用几行代码编写时才应使用。 否则,最好使用老式的目标动作模式。

Thanks for reading!

谢谢阅读!

翻译自: https://medium.com/better-programming/adding-a-closure-as-a-target-to-uibutton-and-other-controls-in-swift-2c5e66029817

swift 闭包作为属性

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值