Create a copy of a UIView in Swift

2019-01-11 02:48发布

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 you'll modifying the other as well.

I have an interesting situation where I would like to add a UIView as a subview in another view, then I make some modifications, and those modifications should not affect the original UIView. How can I make a copy of the UIView so I can ensure I add that copy as a subview instead of a reference to the original UIView?

Note that I can't recreate the view in the same way the original was created, I need some way to create a copy given any UIView object.

标签: ios swift uiview
8条回答
爷、活的狠高调
2楼-- · 2019-01-11 03:35

You can't arbitrarily copy an object. Only objects that implement the NSCopying protocol can be copied.

However, there is a workaround: Since UIViews can be serialized to disk (e.g. to load from a XIB), you could use NSKeyedArchiver and NSKeyedUnarchiver to create a serialized NSData describing your view, then de-serialize that again to get an independent but identical object.

查看更多
冷血范
3楼-- · 2019-01-11 03:36

You must use pattern Prototype

Example of the prototype:

class ThieveryCorporationPersonDisplay {
    var name: String?
    let font: String

    init(font: String) {
        self.font = font
    }

    func clone() -> ThieveryCorporationPersonDisplay {
        return ThieveryCorporationPersonDisplay(font:self.font)
    }
}

An example of using prototype:

let Prototype = ThieveryCorporationPersonDisplay(font:"Ubuntu")

let Philippe = Prototype.clone()
Philippe.name = "Philippe"

let Christoph = Prototype.clone()
Christoph.name = "Christoph"

let Eduardo = Prototype.clone()
Eduardo.name = "Eduardo"
查看更多
登录 后发表回答