How do copy for UILabel?

后端 未结 5 1446
星月不相逢
星月不相逢 2020-12-03 08:21

I have IBOutlet UILabel *label;

and I want to do this

UILabel *label = [titleLabel copy];
label.text = @\"Clone\";
titleLabel.text = @         


        
5条回答
  •  离开以前
    2020-12-03 08:40

    Swift 3 Solution

    I created it as an extension to the UILabel.

    extension UILabel {
        func createCopy() -> UILabel {
            let archivedData = NSKeyedArchiver.archivedData(withRootObject: self)
            return NSKeyedUnarchiver.unarchiveObject(with: archivedData) as! UILabel
        }
    }
    

    How to use

    let anotherNameLabel = nameLabel.createCopy()
    

    Additional Info - How does this work?

    NSKeyedArchiver will take an object from memory and convert it to text. "Keyed" means it uses words to describe the properties of this object, like "LabelFrame", "LabelText", etc. (These are fake keys.) This also called Serialization in other technologies.

    NSKeyedUnarchiver does the opposite. It will take that text and build an object. Here we take that object (Any?) and convert it to a UILabel.

提交回复
热议问题