将闭包作为目标添加到UIButton

问题描述

在开发时请记住这一点,我会尽快发布另一个解决方案。

如果要将闭包作为目标添加UIButton,则必须UIButton使用来向类添加函数extension

import UIKit    
extension UIButton {
    private func actionHandler(action:(() -> Void)? = nil) {
        struct __ { static var action :(() -> Void)? }
        if action != nil { __.action = action }
        else { __.action?() }
    }   
    @objc private func triggerActionHandler() {
        self.actionHandler()
    }   
    func actionHandler(controlEvents control :UIControl.Event, ForAction action:@escaping () -> Void) {
        self.actionHandler(action: action)
        self.addTarget(self, action: #selector(triggerActionHandler), for: control)
    }
}

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: .touchUpInside, 
 ForAction:{() -> Void in
     print("Touch")
 })

解决方法

我有一个通用的控件类,需要根据视图控制器来设置按钮的完成方式。由于setLeftButtonActionWithClosure函数需要将一个闭包作为参数来设置,因此应该将其设置为取消按钮的动作。在Swift中怎么可能因为我们需要将函数名称作为String传递给action:参数。

func setLeftButtonActionWithClosure(completion: () -> Void)
{
self.leftButton.addTarget(<#target: AnyObject?#>,action: <#Selector#>,forControlEvents: <#UIControlEvents#>)
}