Create a copy of a UIView in Swift

后端 未结 7 1864
长发绾君心
长发绾君心 2020-11-29 05:01

Because objects are reference types, not value types, if you set a UIView equal to another UIView, the views are the same object. If you modify one

7条回答
  •  日久生厌
    2020-11-29 05:24

    You can make an UIView extension. In example snippet below, function copyView returns an AnyObject so you could copy any subclass of an UIView, ie UIImageView. If you want to copy only UIView 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: UIView = sourceView.copyView()
    

提交回复
热议问题