Copy UI element in Objective-C

I am trying to set up a UIImagePickerController for iPhone right now. I could change the default buttons (accept and cancel) and also add a few more buttons. But I'm having problems when trying to set up a custom button that looks like the default iPhone. At first I think it would be possible if I got and then cloned the default button as a template for mine by the following code

UIButton *cancelButton = [[[[[[[[[[[[[[[[self.view subviews] objectAtIndex:0]
                            subviews] objectAtIndex:0]
                            subviews] objectAtIndex:0]
                            subviews] objectAtIndex:0]
                            subviews] objectAtIndex:2]
                            subviews] objectAtIndex:0]
                            subviews] objectAtIndex:1]
                            subviews] objectAtIndex:1];


UIButton *anotherButton = [cancelButton copy];

      

But it didn't work due to the fact that I recently learned that NSObject and its subclasses do not implement the NSCopying protocol by default.

I wonder if there is any way - copy the UI element and then change it as my will - create a custom button with an Apple look.

+2


source to share


2 answers


If you want to duplicate any UIView, put it in a nib file and load it as many times as you want.

Another alternative is to archive the existing view and then unlock it. See NSKeyedArchiver Class.



id theButton;  //whatever way you obtain this...
id copyOfTheButton = [NSKeyedUnarchiver unarchiveObjectWithData:
                     [NSKeyedArchiver archivedDataWithRootObject: theButton]];

      

+5


source


There is no easy way to copy an Objective-C object that does not implementNSCopying

(unless you use NSResponder's suggestion of using NSCoding, in which case it is.) There is NSCopyObject()

, but this is perhaps the most dangerous feature in all of Foundation (see NSCopyObject () is considered detrimental to my thoughts on this insane feature).



Your options are safe or dangerous. The safe way is to just copy the appearance of the element into your own code. It's tedious, but generally achievable. A dangerous way is to reverse engineer the element class and interface and try to create your own instance (using alloc / init). It may or may not work, and it may break between OS versions, but it may give you better results, faster. Personally, I try to recreate the original element by hand as best I can. Usually Photoshop is an important part of this job.

+1


source







All Articles