我想将一个UIView复制到另一个视图而不进行归档或取消归档。 如果您有任何解决方案,请帮助我。
我尝试将UIView扩展为已经可用的Stack over flow流程的答案。但是当我用模式图像背景颜色传递视图时它会崩溃。
答案 0 :(得分:2)
与我的评论相关的代码:
extension UIView
{
func copyView() -> UIView?
{
return NSKeyedUnarchiver.unarchiveObjectWithData(NSKeyedArchiver.archivedDataWithRootObject(self)) as? UIView
}
}
我刚刚在Playground中尝试了这个简单的代码来检查复制视图是否有效并且它没有指向相同的视图:
let originalView = UIView(frame: CGRectMake(0, 0, 100, 50));
originalView.backgroundColor = UIColor.redColor();
let originalLabel = UILabel(frame: originalView.frame);
originalLabel.text = "Hi";
originalLabel.backgroundColor = UIColor.whiteColor();
originalView.addSubview(originalLabel);
let copyView = originalView.copyView();
let copyLabel = copyView?.subviews[0] as! UILabel;
originalView.backgroundColor = UIColor.blackColor();
originalLabel.text = "Hola";
originalView.backgroundColor; // Returns black
originalLabel.text; // Returns "Hola"
copyView!.backgroundColor; // Returns red
copyLabel.text; // Returns "Hi"
如果扩展程序不起作用,则copyView
和originalView
将具有相同的backgroundColor
,并且标签的文本也会发生相同的情况。所以也许这个问题可能存在于其他方面。
答案 1 :(得分:0)
func copyView(viewforCopy: UIView) -> UIView {
viewforCopy.hidden = false //The copy not works if is hidden, just prevention
let viewCopy = viewforCopy.snapshotViewAfterScreenUpdates(true)
viewforCopy.hidden = true
return viewCopy
}
func copyView(viewforCopy: UIView) -> UIView {
viewforCopy.isHidden = false //The copy not works if is hidden, just prevention
let viewCopy = viewforCopy.snapshotView(afterScreenUpdates: true)
viewforCopy.isHidden = true
return viewCopy!
}