我只是想知道是否可以将功能传递给按钮动作(通常是选择器).
例如,通常我会说:
UIBarButtonItem(title: "Press",style: .Done,target: self,action: "functionToCall") func functionToCall() { // Do something }
但是我想知道是否可以做一些类似的事情:
UIBarButtonItem(title: "Press",action: { // Do Something })
解决方法
这是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?,actionHandler: ((Void) -> Void)?) { self.init(image: image,action: #selector(barButtonItemPressed)) self.target = self self.actionHandler = actionHandler } func barButtonItemPressed(sender: UIBarButtonItem) { actionHandler?() } }