Clone or Copy UIViewController or UIView

你离开我真会死。 提交于 2019-12-18 04:39:10

问题


UII need copy, self controller or self.view, i have tried:

UIView* viewOfSelf =[self.view copy];
UIViewController* controller = [self copy];

UIView* viewOfSelf =[self.view mutableCopy];
UIViewController* controller = [self mutableCopy];

The error is:

    -[UIViewController mutableCopyWithZone:]: unrecognized selector sent to instance 0xb803490
    -[UIView copyWithZone:]: unrecognized selector sent to instance 0x6e0acb0

回答1:


Use -

NSData *tempArchiveView = [NSKeyedArchiver archivedDataWithRootObject:self.view];
UIView *viewOfSelf = [NSKeyedUnarchiver unarchiveObjectWithData:tempArchiveView];

Similarly -

NSData *tempArchiveViewController = [NSKeyedArchiver archivedDataWithRootObject:self];
UIViewController *controller = [NSKeyedUnarchiver unarchiveObjectWithData:tempArchiveViewController];



回答2:


For an object to be copyable it must implement NSCopying protocol which UIView class nor UIViewController class do not.

If you want to copy a view, I'm pretty sure you're doing something wrong. The copying should be replaced by reusable UIView just like in UITableView using dequeueReusableCellWithIdentifier: method.

Copying view controller is definitely an anti-pattern. If you want exact copy of the view controller that you already have - create a new instance of it with same parameters that current one is.




回答3:


Unfortunately I am not yet allowed to comment, but rishi's solution has one problem: it does not copy NSLayoutConstraints. So if any of your views are using autolayout, those are not going to get copied. I am writing a mini-lib to solve that and will post it to github when done. Unfortunately, I haven't found a ready-to-use solution anywhere.

//Edit

Sorry, what I wrote previously was not completely correct. I did some more research and it turns out that on default, the NSLayoutConstraints in the archived view are NOT saved. But, you can actually specify if you want to archive a constraint by setting its shouldBeArchived property to YES. Then, even after this fake copy, you retain the right constraints in the copied view.



来源:https://stackoverflow.com/questions/10614276/clone-or-copy-uiviewcontroller-or-uiview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!