1

I want to copy one UIView to another view without making it archive or unarchive. 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. But its crashing when I pass the view with pattern Image Background color.

2 Answers2

3

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:

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. So maybe there is the possibility that the problem is in other part.

crisisGriega
  • 852
  • 7
  • 17
  • I've just double checked it in a Playground and the copy is working fine. So I've just updated my answer with the code I used in case you can find it helpful – crisisGriega Jul 20 '16 at 08:57
  • Don't take fix color....use some image for background color. Then its not working. – Bhuvanendra Pratap Maurya Jul 20 '16 at 09:58
  • Oh right, sorry. Then your problem is not copying a UIView is encoding an UIColor when it's created from a pattern. You can find a solution to that problem [here](http://stackoverflow.com/a/7477462/1387646) – crisisGriega Jul 20 '16 at 10:51
-1

Original Post

   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
    }

Updated for Swift 4

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!
}
Klowne
  • 59
  • 8
jose920405
  • 7,982
  • 6
  • 45
  • 71
  • 6
    This does not copy the view with its live hierarchy. It produces a static picture of the view at the time `snapshotView...` was called. – jscs Oct 24 '17 at 00:30