Copy UI element in Objective-C
I'm trying to customize the UIImagePickerController for iPhone right now. I could modify the default buttons (take and cancel) as well as add more buttons. But I have trouble when attempting to make the customized button look-and-feel like the default iPhone's ones. At first I think that it'd be possible if I get and then clone the default button as a template for mine by the following code
UIButton *cancelButton = [[[[[[[[[[[[[[[[self.view subviews] objectAtInd开发者_JAVA百科ex: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 didnt work due to the fact I have just known lately that NSObject and its subclasses dont implement the protocol NSCopying by default.
I wonder is there any way to either - copy an UI element and then modify it as my will - create a custom button with the look of Apple's ones
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 an existing view and then unarchive it. See the NSKeyedArchiver class.
id theButton; //whatever way you obtain this...
id copyOfTheButton = [NSKeyedUnarchiver unarchiveObjectWithData:
[NSKeyedArchiver archivedDataWithRootObject: theButton]];
There is no easy way to copy an Objective-C object that does not implement (unless you use NSResponder's suggestion of using NSCoding, in which case there is.) There is NSCopying
NSCopyObject()
, but this is perhaps the most dangerous function in all of Foundation (see NSCopyObject() considered harmful for my thoughts on this insane function).
Your options are safe or dangerous. The safe way is to just copy the look and feel of the element in your own code. This is tedious, but generally achievable. The dangerous way is to reverse engineer the element's class and interface and try to create your own instance (with alloc/init). This might work and it might not, and it may break between versions of the OS, but it may give you better results, faster. Personally, I tend towards just recreating the original element by hand as best you can. Generally Photoshop is an important part of that work.
精彩评论