开发者

Duplicate, clone or copy UIView

开发者 https://www.devze.com 2023-02-11 02:50 出处:网络
I have a UIView that is linked to a UIViewController via the Interface Builder. Is it possible to duplicate, clone or copy this 开发者_StackOverflow社区view so that I can use it more than once?The fol

I have a UIView that is linked to a UIViewController via the Interface Builder. Is it possible to duplicate, clone or copy this 开发者_StackOverflow社区view so that I can use it more than once?


The following category might not be particularly efficient, but worked for me in one project:

@implementation UIView (OPCloning)

- (id) clone {
    NSData *archivedViewData = [NSKeyedArchiver archivedDataWithRootObject: self];
    id clone = [NSKeyedUnarchiver unarchiveObjectWithData:archivedViewData];
    return clone;
}

@end

I'd not implement -copy or -copyWithZone: as Apple might do so in the future. Note, that not all views implement archiving to the same extent. You'll definitely need to implement the NSCoding methods for custom properties of your NSView subclasses to be cloned (will turn to nil in the cloned view, otherwise). Still easier than writing custom cloning code.


Here is a new method you can use: Use UIView's method:

- (UIView *)snapshotViewAfterScreenUpdates:(BOOL)afterUpdates

This is the fastest way to draw a view. Available in iOS 7.


You can try with Swift 3.0.1 below:

extension UIView{
func copyView() -> AnyObject{
    return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self))! as AnyObject
 }
}


Sure. The documentation has a good example of how to achieve that; it's for UITableViewCell, but is a good approach to use here as well.

Depending on the complexity of your view, you might want to make it a custom view class, and give it its own IBOutlet properties for whatever subviews it has; in that case, you'd set the “Class Identity” of the view in Interface Builder to that class. Then your view controller could access those views on any given XIB-loaded view via, for instance, myLoadedView.someLabel, rather than having to use, e.g., [myLoadedView viewWithTag:3] as suggested by the aforelinked documentation.

0

精彩评论

暂无评论...
验证码 换一张
取 消