How to add tap function to UIButton

January 29, 2019

One of the most annoyances in iOS development is to programmatically handle a tap action for a UIButton. In Android all views have an OnClickListener which removes the need to use addTarget and @selector and creating a separate function to add the selector. Here is a simply solution to add an OnClickListener just like Android:

UIButton+Tap.swift

import UIKit

/// A Convience TypeAlias to a View OnClickListener.
public typealias OnClickListener = (UIView) -> ()

/// Represents the Base UIButton for Buttons used in a Howdi Application.
open class OnClickButton: UIButton {
    public var onClickListener: OnClickListener?
    public var assocatiedValue: Any?
    
    // MARK: - Functions
    public override init(frame: CGRect) {
        super.init(frame: frame)
        isUserInteractionEnabled = true
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    open override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        addTarget(self, action:#selector(self.handleClick(_:)), for: .touchUpInside)
    }
    
    @objc open func handleClick(_ button: UIButton){
        guard let onClickListener = onClickListener else { return }
        onClickListener(button)
    }
}

Usage:

let button = OnClickButton()
button.onClickListener = { _ in 
   // Handle button click action
}