Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to duplicate a UIButton in Objective C?

Tags:

The object inherits from NSObject.

Is there a method to create a copy of it as a new object?

like image 415
James Skidmore Avatar asked Jul 07 '09 15:07

James Skidmore


People also ask

How do you duplicate a button in Swift?

For quick use, you can just click alt key and drag the button you want to duplicate. Even command + c and command + v works well.


2 Answers

UIButton does not conform to NSCopying, so you cannot make a copy via -copy.

However, it does conform to NSCoding, so you can archive the current instance, then unarchive a 'copy'.

NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject: button]; UIButton *buttonCopy = [NSKeyedUnarchiver unarchiveObjectWithData: archivedData]; 

Afterwards, you'll have to assign any additional properties that weren't carried over in the archive (e.g. the delegate) as necessary.

like image 95
Jim Correia Avatar answered Sep 28 '22 18:09

Jim Correia


UIButton doesn't conform to the NSCopying protocol, so you have copy it by hand. On the other hand, it is not a bad thing, since it is not exactly clear what does it mean to copy a button. For example, should it add the button copy to the same view the original is in? Should it fire the same methods when tapped?

like image 27
Marco Mustapic Avatar answered Sep 28 '22 18:09

Marco Mustapic