【发布时间】:2014-03-26 07:59:44
【问题描述】:
我有许多案例,每个案例都会生成不同的图像。问题是,图像在生成后似乎会堆叠。如何设置每个案例以覆盖以前的图像?
- (void)setTileValue:(NSInteger)tileValue {
_tileValue = tileValue;
self.numberLabel.text = [@(tileValue) stringValue];
UIImageView *backgroundView = [self backgroundView:[@(tileValue) intValue]];
[self.numberLabel addSubview:backgroundView];
self.value = tileValue;
}
- (UIImageView *)backgroundView:(NSUInteger)value {
switch (value) {
case 1:
return [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background"]]; // light gray
case 2:
return [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background1"]]; // gray
case 4:
return [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background2"]]; // gark gray
case 8:
return [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background3"]]; // red
case 16:
return [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background4"]]; // orange
default:
return [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background"]];
}
}
更新的代码:所以程序每次都使用 initWithImage 创建一个新图像。我现在将返回设置为只返回 UIImage。为什么这段代码也不能解决问题?
- (void)setTileValue:(NSInteger)tileValue {
_tileValue = tileValue;
self.numberLabel.text = [@(tileValue) stringValue];
// UIImageView *backgroundView = [self backgroundView:[@(tileValue) intValue]];
UIImageView *backgroundView = [[UIImageView alloc] initWithImage:[self tileBG:[@(tileValue) intValue]]]; [self.numberLabel addSubview:backgroundView];
self.numberLabel.backgroundColor = [self tileColorForValue:[@(tileValue) intValue]];
self.backgroundColor = [self tileColorForValue:[@(tileValue) intValue]];
self.numberLabel.textColor = [self numberColorForValue:[@(tileValue) intValue]];
self.value = tileValue;
}
- (UIColor *)defaultBackgroundColor {
return [UIColor lightGrayColor];
}
- (UIColor *)defaultNumberColor {
return [UIColor colorWithWhite:0.0 alpha:0.0];
}
- (UIImage *)tileBG:(NSUInteger)value {
switch (value) {
case 1:
return [UIImage imageNamed:@"background"]; // light gray
case 2:
return [UIImage imageNamed:@"background1"]; // gray
case 4:
return [UIImage imageNamed:@"background2"]; // gark gray
case 8:
return [UIImage imageNamed:@"background3"]; // red
case 16:
return [UIImage imageNamed:@"background4"]; // red
case 32:
return [UIImage imageNamed:@"background5"]; // red
default:
return [UIImage imageNamed:@"background"]; // red
}
}
【问题讨论】:
-
只需返回一个 UIImage 而不是 UIImageView 并将返回的图像设置为 UIImageView 的 .image 属性。旁注:它会堆积起来,因为您每次都返回 UIImageView。不应该那样做。
-
谢谢。我现在将 return 设置为返回 UIImage。这个问题似乎仍然存在。
-
问题出在 setTitleValue 方法中。每当调用此代码时,您都在添加 UIImageView。为什么不为 UIImageView 保留一个属性,而不是在每次调用 setTitle 时添加它?
-
哦,我明白了。如何为 UIImageView 创建单独的属性?
-
或者在 setTileView 中添加另一个图像之前删除上一个图像会更简单吗?
标签: ios objective-c switch-statement