我使用colorWithPatternImage来设置UILabel的背景图像,但是当我将其存档时,我收到以下错误:
NSInternalInconsistencyException', reason: 'Only support RGBA or the White color space, this method is a hack.'
在哪种情况下,我猜这是一个黑客。我的问题是:是否可以将图像存档为标签背景的一部分? 我已经将UILabel子类化了一个不同的原因,为了将图像设置为现有子类的背景,我可以添加任何内容吗?
为清楚起见,这是导致问题的代码:
NSData *viewData = [NSKeyedArchiver archivedDataWithRootObject:label];
其中label是具有背景图像集的UILabel,使用colorWithPatternImage。
干杯!
答案 0 :(得分:0)
听起来像是和
有同样的问题Saving [UIColor colorWithPatternImage:image] UIColor to Core Data using NSKeyedArchiver
答案 1 :(得分:0)
另一个选项是在你的UILabel子类中,你创建了一个用于存储模式图像的ivar并且你存档了ivar。取消归档UILabel子类时,使用图像ivar重新创建模式图像。
标签的示例代码。
@implementation ESKLabelArchive
@synthesize backgroundImage=_backgroundImage;
#pragma mark - NSCoding Protocols
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self)
{
self.backgroundImage = (UIImage *)[aDecoder decodeObjectForKey:@"backgroundImage"];
if (self.backgroundImage != nil)
self.backgroundColor = [UIColor colorWithPatternImage:self.backgroundImage];
}
return self;
}
- (void)setBackgroundImage:(UIImage *)backgroundImage
{
_backgroundImage = [backgroundImage copy];
self.backgroundColor = [UIColor colorWithPatternImage:_backgroundImage];
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
if (self.backgroundImage != nil)
{
self.backgroundColor = [UIColor clearColor];
[aCoder encodeObject:self.backgroundImage forKey:@"backgroundImage"];
}
[super encodeWithCoder:aCoder];
if (self.backgroundImage != nil)
{
self.backgroundColor = [UIColor colorWithPatternImage:self.backgroundImage];
}
}
@end
Sampel View Controller
@implementation ESKViewController
@synthesize label;
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (IBAction)archivedTapped:(id)sender
{
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:self.label forKey:@"label"];
[archiver finishEncoding];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
ESKLabelArchive *label2 = [unarchiver decodeObjectForKey:@"label"];
[unarchiver finishDecoding];
label2.text = @"unarchived";
label2.frame = CGRectMake(20, 150, 200, 100);
[self.view addSubview:label2];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.label.backgroundImage = [UIImage imageNamed:@"ricepaper.png"];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.label = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
@end