ios – 将关闭作为目标添加到UIButton

我有一个通用控件类,需要根据视图控制器设置按钮的完成.因此,setLeftButtonActionWithClosure函数需要将一个关闭作为参数,该闭包应该被设置为一个unbutton的动作.如何在 Swift中因为我们需要将函数名称作为String传递给action:parameter.
func setLeftButtonActionWithClosure(completion: () -> Void)
{
self.leftButton.addTarget(<#target: AnyObject?#>,action: <#Selector#>,forControlEvents: <#UIControlEvents#>)
}

解决方法

注意:
像@EthanHuang说
“如果您有两个以上的实例,此解决方案将不起作用,所有操作将被最后一次分配覆盖.
记住这一点,当你开发,我会尽快发布另一个解决方案.

如果要将一个闭包作为目标添加到UIButton,则必须通过使用扩展名将函数添加到UIButton类

import UIKit

extension UIButton {
    private func actionHandleBlock(action:(() -> Void)? = nil) {
        struct __ {
            static var action :(() -> Void)?
        }
        if action != nil {
            __.action = action
        } else {
            __.action?()
        }
    }

    @objc private func triggerActionHandleBlock() {
        self.actionHandleBlock()
    }

    func actionHandle(controlEvents control :UIControlEvents,ForAction action:() -> Void) {
        self.actionHandleBlock(action)
        self.addTarget(self,action: "triggerActionHandleBlock",forControlEvents: control)
    }
}

和电话:

let button = UIButton()
 button.actionHandle(controlEvents: UIControlEvents.TouchUpInside,ForAction:{() -> Void in
     print("Touch")
 })

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...