[英]how to copy one view to another view in Swift
I want to copy one UIView to another view without making it archive or unarchive. 我想将一个UIView复制到另一个视图而不进行存档或取消存档。 Please help me if you have any solution.
如果您有任何解决方案,请帮助我。
I tried with by making an extension of UIView as already available an answer on Stack over flow. 我尝试通过扩展UIView作为已经可用的Stack over flow的答案。 But its crashing when I pass the view with pattern Image Background color.
但是当我通过带有图案图像背景颜色的视图时,它崩溃了。
The code related to my comment below: 与我的评论相关的代码如下:
extension UIView
{
func copyView() -> UIView?
{
return NSKeyedUnarchiver.unarchiveObjectWithData(NSKeyedArchiver.archivedDataWithRootObject(self)) as? UIView
}
}
I've just tried this simple code in a Playground to check that the copy view works and it's not pointing the same view: 我刚刚在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"
If the extension wouldn't work, both copyView
and originalView
would have same backgroundColor
and the same would happen to the text of the labels. 如果扩展名不起作用,则
copyView
和originalView
都将具有相同的backgroundColor
并且标签的文本也将发生相同的情况。 So maybe there is the possibility that the problem is in other part. 因此,也许问题可能出在另一部分。
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!
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.