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. 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.

Upvotes: 1

Views: 7999

Answers (2)

jose920405
jose920405

Reputation: 8057

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!
}

Upvotes: -1

crisisGriega
crisisGriega

Reputation: 862

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.

Upvotes: 3

Related Questions