Can UIView be copied?

后端 未结 6 1610
广开言路
广开言路 2020-11-27 15:02

Simply using this way:

UIView* view2 = [view1 copy]; // view1 existed

This will cause simulator can not launch this app.

Try retai

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 15:35

    You can make an UIView extension. In example swift snippet below, function copyView returns an AnyObject so you could copy any subclass of an UIView, ie UIImageView. If you want to copy only UIViews you can change the return type to UIView.

    //MARK: - UIView Extensions
    
        extension UIView
        {
           func copyView() -> T {
                return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self)) as! T
           }
        }
    

    Example usage:

    let sourceView = UIView()
    let copiedView = sourceView.copyView()
    

提交回复
热议问题