Introduction

suggest change

Typically, when using UIControl or UIButton, we add a selector as a callback action for when an event occurs on a button or control, such as the user pressing the button or touching the control.

For example, we would do the following:

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var button: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 44))
        button.addTarget(self, action: #selector(self.onButtonPress(_:)), for: .touchUpInside)
        self.view.addSubview(button)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    func onButtonPress(_ button: UIButton!) {
        print("PRESSED")
    }
}

When it comes to selector, the compiler only needs to know that a method exists. That can be an optional protocol method the class does not implement.

For example, the following would crash your application:

import UIKit

@objc
protocol ButtonEvent {
    @objc optional func onButtonPress(_ button: UIButton)
}

class ViewController: UIViewController, ButtonEvent {
    @IBOutlet weak var button: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 44))
        button.addTarget(self, action: #selector(ButtonEvent.onButtonPress(_:)), for: .touchUpInside)
        self.view.addSubview(button)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

This is because your application does NOT implement the onButtonPress function.

Now what if you could do all of this alongside the initialization of the button? What if you didn’t have to specify callbacks and could instead specify blocks that can be added and removed at any time? Why worry about implementing selectors?


Solution

import Foundation
import UIKit

protocol RemovableTarget: class {
    func enable()
    func disable()
}

extension UIControl {
    func addEventHandler(event: UIControlEvents, runnable: @escaping (UIControl) -> Void) -> RemovableTarget {

        class Target: RemovableTarget {
            private var event: UIControlEvents
            private weak var control: UIControl?
            private var runnable: (UIControl) -> Void

            init(event: UIControlEvents, control: UIControl, runnable: @escaping (UIControl) -> Void) {
                self.event = event
                self.control = control
                self.runnable = runnable
            }

            @objc func run(_ control: UIControl) {
                runnable(control)
            }

            func enable() {
                control?.addTarget(self, action: #selector(Target.run(_:)), for: event)
                guard let control = control else { return }
                objc_setAssociatedObject(control, Unmanaged.passUnretained(self).toOpaque(), self, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }

            func disable() {
                control?.removeTarget(self, action: #selector(Target.run(_:)), for: event)
                guard let control = control else { return }
                objc_setAssociatedObject(control, Unmanaged.passUnretained(self).toOpaque(), nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }

        let target = Target(event: event, control: self, runnable: runnable)
        target.enable()
        return target
    }
}

The extension above is Swift 3, matching the button samples. The original closure type (control: UIControl) -> Void and private protocol methods do not compile together with those samples. enable and disable cannot be private if they satisfy RemovableTarget.

UIControl does not retain its targets. The original code associated the target with itself, which does not keep the control from dropping it. The target is now retained as an associated object of the control. unsafeAddress(of:) is an old Swift function. This uses Unmanaged.passUnretained(self).toOpaque() as the key.

The event handler function returns a Protocol in order to hide the inner workings of the Target class but also to allow you to enable and disable the target at any given time.


Usage Example:

import Foundation
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        

        //Create a button.
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 44))
        
        //Add an event action block/listener -- Handles Button Press.
        let target = button.addEventHandler(event: .touchUpInside) { (control) in
            print("Pressed")
        }
        

        self.view.addSubview(button)
        
        //Example of enabling/disabling the listener/event-action-block.
        DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
            target.disable() //Disable the listener.

            DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
                target.enable() //Enable the listener.
            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents