要复制按钮,此方法工作正常:
NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject: btn];
UIButton *newButton = [NSKeyedUnarchiver unarchiveObjectWithData: archivedData];
但是,自iOS12开始,此功能已被弃用。但是使用建议的方法会使newButton为nil。我在做什么错了,或者确实有另一种方法可以复制UIButton。完整代码:
// Init originalBtnsArray and
originalBtnsArray = [[NSMutableArray alloc]init];
// Populate originalBtnsArray
for (UIButton *btn in btnsReferencesArray){
// Below works but is now deprecated as of iOS 12
//NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject: btn];
//UIButton *newButton = [NSKeyedUnarchiver unarchiveObjectWithData: archivedData];
NSError* error = nil;
NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject:btn requiringSecureCoding:NO error:&error];
NSError* unArchiveError = nil;
UIButton *newButton = [NSKeyedUnarchiver unarchivedObjectOfClass:[UIButton class] fromData:archivedData error:&unArchiveError];
// newButton is nil, which is suboptimal
[originalBtnsArray addObject:newButton];
}
最佳答案
现在可以正常工作了:
UIButton *newButton = [[UIButton alloc]init];
newButton.frame = btn.frame;
[originalBtnsArray addObject:newButton];