Swift使用选择器参数,如闭包 [英] Swift use selector argument like a closure

查看:125
本文介绍了Swift使用选择器参数,如闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道是否可以将一个函数传递给一个按钮动作(通常是一个选择器)。

I was just wondering if it was possible to pass a function to a button action (which is usually a selector).

例如,通常我会说:

UIBarButtonItem(title: "Press", style: .Done, target: self, action: "functionToCall")

func functionToCall() {
    // Do something
}

但我想知道是否可以做以下事情:

But I was wondering if it's possible to do something like:

UIBarButtonItem(title: "Press", style: .Done, target: self, action: {
    // Do Something
})

我想这样做的原因是因为我的功能非常简单,看起来它更整洁,更像Swift一样,它们强调它们放在闭包上。

Reason I want to do this is because my function is super simple and it seems like it would be neater and more Swift-like what with the emphasis they are placing on closures.

推荐答案

这是Swift 3的更新解决方案。

Here's an updated solution for Swift 3.

class BlockBarButtonItem: UIBarButtonItem {
  private var actionHandler: ((Void) -> Void)?

  convenience init(title: String?, style: UIBarButtonItemStyle, actionHandler: ((Void) -> Void)?) {
    self.init(title: title, style: style, target: nil, action: #selector(barButtonItemPressed))
    self.target = self
    self.actionHandler = actionHandler
  }

  convenience init(image: UIImage?, style: UIBarButtonItemStyle, actionHandler: ((Void) -> Void)?) {
    self.init(image: image, style: style, target: nil, action: #selector(barButtonItemPressed))
    self.target = self
    self.actionHandler = actionHandler
  }

  func barButtonItemPressed(sender: UIBarButtonItem) {
    actionHandler?()
  }
}

这篇关于Swift使用选择器参数,如闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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