How to duplicate a UIButton in Objective C?

后端 未结 6 669
梦谈多话
梦谈多话 2020-12-24 02:35

The object inherits from NSObject.

Is there a method to create a copy of it as a new object?

6条回答
  •  暖寄归人
    2020-12-24 03:09

    UIButton does not conform to NSCopying, so you cannot make a copy via -copy.

    However, it does conform to NSCoding, so you can archive the current instance, then unarchive a 'copy'.

    NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject: button];
    UIButton *buttonCopy = [NSKeyedUnarchiver unarchiveObjectWithData: archivedData];
    

    Afterwards, you'll have to assign any additional properties that weren't carried over in the archive (e.g. the delegate) as necessary.

提交回复
热议问题