Skip to content

Instantly share code, notes, and snippets.

@boherna
Created June 17, 2018 12:57
Show Gist options
  • Save boherna/3192ca1f6a126e6e6d4f221e3b2c418c to your computer and use it in GitHub Desktop.
Save boherna/3192ca1f6a126e6e6d4f221e3b2c418c to your computer and use it in GitHub Desktop.
How to copy a UIButton using Swift
public extension UIButton {
func copy<T: UIButton>(withControlEvents controlEvents: [UIControlEvents]) -> T? {
let data = NSKeyedArchiver.archivedData(withRootObject: self)
guard let copy = NSKeyedUnarchiver.unarchiveObject(with: data) as? T else { return nil }
if let font = titleLabel?.font {
copy.titleLabel?.font = font
}
if let lineBreakMode = titleLabel?.lineBreakMode {
copy.titleLabel?.lineBreakMode = lineBreakMode
}
if let textAlignment = titleLabel?.textAlignment {
copy.titleLabel?.textAlignment = textAlignment
}
controlEvents.forEach { controlEvent in
allTargets.forEach { target in
actions(forTarget: target, forControlEvent: controlEvent)?.forEach { action in
copy.addTarget(target, action: Selector(action), for: controlEvent)
}
}
}
return copy
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment