Swift programmatically create function for button

2020-03-17 04:03发布

In Swift you can create a function for a button like this:

button.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)

However is there a way I can do something like this:

button.whenButtonIsClicked({Insert code here})

That way I do not even have too declare an explicit function for the button. I know I can use button tags but I would prefer to do this instead.

5条回答
唯我独甜
2楼-- · 2020-03-17 04:42

This one will work ! Make sure you don't alter the tag for buttons

extension UIButton {
private func actionHandleBlock(action:(()->())? = nil) {
    struct __ {
        var closure : (() -> Void)?
        typealias EmptyCallback = ()->()
        static var action : [EmptyCallback] = []
    }
    if action != nil {
       // __.action![(__.action?.count)!] = action!
        self.tag = (__.action.count)
        __.action.append(action!)
    } else {
        let exe = __.action[self.tag]
        exe()
    }
}

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

func addAction(forControlEvents control :UIControlEvents, ForAction action:@escaping () -> Void) {
    self.actionHandleBlock(action: action)
    self.addTarget(self, action: #selector(triggerActionHandleBlock), for: control)
}

}

查看更多
▲ chillily
3楼-- · 2020-03-17 04:46
let bt1 = UIButton(type: UIButtonType.InfoDark)
    bt1.frame = CGRectMake(130, 80, 40, 40)

    let bt2 = UIButton(type: UIButtonType.RoundedRect)
    bt2.frame = CGRectMake(80, 180, 150, 44)
    bt2.backgroundColor = UIColor.purpleColor()
    bt2.tintColor = UIColor.yellowColor()
    bt2.setTitle("Tap Me", forState: UIControlState.Normal)
    bt2.addTarget(self, action: "buttonTap", forControlEvents: UIControlEvents.TouchUpInside)

    let bt3 = UIButton(type: UIButtonType.RoundedRect)
    bt3.backgroundColor = UIColor.brownColor()
    bt3.tintColor = UIColor.redColor()
    bt3.setTitle("Tap Me", forState: UIControlState.Normal)
    bt3.frame = CGRectMake(80, 280, 150, 44)
    bt3.layer.masksToBounds = true
    bt3.layer.cornerRadius = 10
    bt3.layer.borderColor = UIColor.lightGrayColor().CGColor

    self.view.addSubview(bt1)
    self.view.addSubview(bt2)
    self.view.addSubview(bt3)

}

func buttonTap(button:UIButton)
{
    let alert = UIAlertController(title: "Information", message: "UIButton Event", preferredStyle: UIAlertControllerStyle.Alert)
    let OKAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)
    alert.addAction(OKAction)
}
查看更多
一纸荒年 Trace。
4楼-- · 2020-03-17 04:51

Create your own UIButton subclass to do this:

class MyButton: UIButton {
    var action: (() -> Void)?

    func whenButtonIsClicked(action: @escaping () -> Void) {
        self.action = action
        self.addTarget(self, action: #selector(MyButton.clicked), for: .touchUpInside)
    }

    // Button Event Handler:
    // I have not marked this as @IBAction because it is not intended to
    // be hooked up to Interface Builder       
    @objc func clicked() {
        action?()
    }
}

Substitute MyButton for UIButton when you create buttons programmatically and then call whenButtonIsClicked to set up its functionality.

You can also use this with UIButtons in a Storyboard (just change their class to MyButton) and then call whenButtonIsClicked in viewDidLoad.

@IBOutlet weak var theButton: MyButton!

var count = 0

override func viewDidLoad() {
    super.viewDidLoad()

    // be sure to declare [unowned self] if you access
    // properties or methods of the class so that you
    // don't create a strong reference cycle
    theButton.whenButtonIsClicked { [unowned self] in
        self.count += 1
        print("count = \(self.count)")
    }

A much more capable implementation

Recognizing the fact that programmers might want to handle more events than just .touchUpInside, I wrote this more capable version which supports multiple closures per UIButton and multiple closures per event type.

class ClosureButton: UIButton {
    private var actions = [UInt : [((UIControl.Event) -> Void)]]()

    private let funcDict: [UInt : Selector] = [
        UIControl.Event.touchCancel.rawValue:       #selector(eventTouchCancel),
        UIControl.Event.touchDown.rawValue:         #selector(eventTouchDown),
        UIControl.Event.touchDownRepeat.rawValue:   #selector(eventTouchDownRepeat),
        UIControl.Event.touchUpInside.rawValue:     #selector(eventTouchUpInside),
        UIControl.Event.touchUpOutside.rawValue:    #selector(eventTouchUpOutside),
        UIControl.Event.touchDragEnter.rawValue:    #selector(eventTouchDragEnter),
        UIControl.Event.touchDragExit.rawValue:     #selector(eventTouchDragExit),
        UIControl.Event.touchDragInside.rawValue:   #selector(eventTouchDragInside),
        UIControl.Event.touchDragOutside.rawValue:  #selector(eventTouchDragOutside)
    ]

    func handle(events: [UIControl.Event], action: @escaping (UIControl.Event) -> Void) {
        for event in events {
            if var closures = actions[event.rawValue] {
                closures.append(action)
                actions[event.rawValue] = closures
            } else {
                guard let sel = funcDict[event.rawValue] else { continue }
                self.addTarget(self, action: sel, for: event)
                actions[event.rawValue] = [action]
            }
        }
    }

    private func callActions(for event: UIControl.Event) {
        guard let actions = actions[event.rawValue] else { return }
        for action in actions {
            action(event)
        }
    }

    @objc private func eventTouchCancel()       { callActions(for: .touchCancel) }
    @objc private func eventTouchDown()         { callActions(for: .touchDown) }
    @objc private func eventTouchDownRepeat()   { callActions(for: .touchDownRepeat) }
    @objc private func eventTouchUpInside()     { callActions(for: .touchUpInside) }
    @objc private func eventTouchUpOutside()    { callActions(for: .touchUpOutside) }
    @objc private func eventTouchDragEnter()    { callActions(for: .touchDragEnter) }
    @objc private func eventTouchDragExit()     { callActions(for: .touchDragExit) }
    @objc private func eventTouchDragInside()   { callActions(for: .touchDragInside) }
    @objc private func eventTouchDragOutside()  { callActions(for: .touchDragOutside) }
}

Demo

class ViewController: UIViewController {

    var count = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        let button = ClosureButton(frame: CGRect(x: 50, y: 100, width: 60, height: 40))
        button.setTitle("press me", for: .normal)
        button.setTitleColor(.blue, for: .normal)

        // Demonstration of handling a single UIControl.Event type.
        // If your closure accesses self, be sure to declare [unowned self]
        // to prevent a strong reference cycle
        button.handle(events: [.touchUpInside]) { [unowned self] _ in
            self.count += 1
            print("count = \(self.count)")
        }

        // Define a second handler for touchUpInside:
        button.handle(events: [.touchUpInside]) { _ in
            print("I'll be called on touchUpInside too")
        }

        let manyEvents: [UIControl.Event] = [.touchCancel, .touchUpInside, .touchDown, .touchDownRepeat, .touchUpOutside, .touchDragEnter,
             .touchDragExit, .touchDragInside, .touchDragOutside]

        // Demonstration of handling multiple events
        button.handle(events: manyEvents) { event in
            switch event {
            case .touchCancel:
                print("touchCancel")
            case .touchDown:
                print("touchDown")
            case .touchDownRepeat:
                print("touchDownRepeat")
            case .touchUpInside:
                print("touchUpInside")
            case .touchUpOutside:
                print("touchUpOutside")
            case .touchDragEnter:
                print("touchDragEnter")
            case .touchDragExit:
                print("touchDragExit")
            case .touchDragInside:
                print("touchDragInside")
            case .touchDragOutside:
                print("touchDragOutside")
            default:
                break
            }
        }

        self.view.addSubview(button)
    }
}
查看更多
我欲成王,谁敢阻挡
5楼-- · 2020-03-17 05:00

If you don't want to do anything "questionable" (i.e., using Objective-C's dynamic capabilities, or adding your own touch handlers, etc.) and do this purely in Swift, unfortunately this is not possible.

Any time you see #selector in Swift, the compiler is calling objc_MsgSend under the hood. Swift doesn't support Objective-C's dynamicism. For better or for worse, this means that in order to swap out the usage of this selector with a block, you'd probably need to perform some black magic to make it work, and you'd have to use Objective-C constructs to do that.

If you don't have any qualms about doing "yucky dynamic Objective-C stuff", you could probably implement this by defining an extension on UIButton, and then associate a function to the object dynamically using associated objects. I'm going to stop here, but if you want to read more, NSHipster has a great overview on associated objects and how to use them.

查看更多
Juvenile、少年°
6楼-- · 2020-03-17 05:03

You can also just subclass UIView and have a property that is a closure like vacawama has.

var action: () -> ()? 

Then override the touchesBegan method to call the function whenever the button is touched. With this approach though you don't get all the benefits of starting with a UIBitton.

查看更多
登录 后发表回答