Skip to content

Instantly share code, notes, and snippets.

@aataraxiaa
Created September 4, 2017 13:10
Show Gist options
  • Save aataraxiaa/365fc75de4497a37ce0d69b5bec60a10 to your computer and use it in GitHub Desktop.
Save aataraxiaa/365fc75de4497a37ce0d69b5bec60a10 to your computer and use it in GitHub Desktop.
UIButton extension which enables the caller to duplicate a UIButton
//
// UIButton+Duplicate.swift
//
// Created by Peter Smith on 04/09/2017.
//
import UIKit
/// UIButton extension which enables the caller to duplicate a UIButton
extension UIButton {
/// Creates a duplicate of the terget UIButton
/// The caller specified the UIControlEvent types to copy across to the duplicate
///
/// - Parameter controlEvents: UIControlEvent types to copy
/// - Returns: A UIButton duplicate of the original button
func duplicate(forControlEvents controlEvents: [UIControlEvents]) -> UIButton? {
// Attempt to duplicate button by archiving and unarchiving the original UIButton
let archivedButton = NSKeyedArchiver.archivedData(withRootObject: self)
guard let buttonDuplicate = NSKeyedUnarchiver.unarchiveObject(with: archivedButton) as? UIButton else { return nil }
// Copy targets and associated actions
self.allTargets.forEach { target in
controlEvents.forEach { controlEvent in
self.actions(forTarget: target, forControlEvent: controlEvent)?.forEach { action in
buttonDuplicate.addTarget(target, action: Selector(action), for: controlEvent)
}
}
}
return buttonDuplicate
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment