我使用此代码
创建了多个标签.H文件
@interface ViewController : UIViewController
{
NSArray * phraseAry ;
UIView * containerView;
UILabel * oldLabel;
NSMutableArray *dataArray;
}
@property (strong, nonatomic) IBOutlet UIScrollView *myScrollView;
.M文件
- (void)viewDidLoad
{
[super viewDidLoad];
heightValue = 20;
widthValue = 0;
xValue = 5;
yValue = 10;
containerView = [[UIView alloc] init];
for (int i=0; i<phraseAry.count; i++) {
widthValue = [self returnWidth:[phraseAry objectAtIndex:i]];
int newXValue = xValue+widthValue+5;
//NSLog(@"newXValue : %i",newXValue);
if (newXValue > 310) {
yValue +=20;
xValue = 5;
newXValue = xValue+widthValue+5;
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(xValue, yValue, widthValue, heightValue)];
lbl.text = [phraseAry objectAtIndex:i];
[lbl setFont:[UIFont fontWithName:@"Helvetica" size:14.0]];
lbl.tag = i;
lbl.textColor = [UIColor colorWithRed:(92/255.0) green:(109/255.0) blue:(43/255.0) alpha:1];
[containerView addSubview:lbl];
xValue = newXValue;
} else {
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(xValue, yValue, widthValue, heightValue)];
lbl.text = [phraseAry objectAtIndex:i];
[lbl setFont:[UIFont fontWithName:@"Helvetica" size:14.0]];
lbl.tag = i;
lbl.textColor = [UIColor colorWithRed:(92/255.0) green:(109/255.0) blue:(43/255.0) alpha:1];
[containerView addSubview:lbl];
xValue = newXValue;
}
}
containerView.frame = CGRectMake(0, 0, 320, yValue);
//add code to customize, e.g. polygonView.backgroundColor = [UIColor blackColor];
[self.myScrollView addSubview:containerView];
self.myScrollView.contentSize = containerView.frame.size;
}
而且我使用此代码在特定表格中设置背景颜色和textcolor
- (void)updateLabelMethod
{
oldLabel.backgroundColor = [UIColor clearColor];
UILabel *label = (UILabel *)[containerView viewWithTag:2];
oldLabel = label;
label.backgroundColor = [UIColor colorWithRed:(98/255.0) green:(147/255.0) blue:(216/255.0) alpha:1];
label.textColor = [UIColor whiteColor];
containerView.backgroundColor = [UIColor clearColor];
}
它会更新标签的背景,但是当我使用此代码更新textcolor时,它会显示错误
由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:' - [UIView setTextColor:]:无法识别的选择器发送到实例0xbaa3b30'
任何设置textcolor的方法? Plz帮助。
答案 0 :(得分:3)
从1而不是0开始标签标签,因为默认情况下,所有视图的标签值均为0。
lbl.tag = i+1;
因为
UILabel *label = (UILabel *)[containerView viewWithTag:0];
它会返回containerView
本身,UIView
没有textColor
属性:P
答案 1 :(得分:1)
[containerView viewWithTag:2];
检查容器视图只有一个视图,它是带有标记2的标签。 可能是其他一些视图设置为标记2,可能导致问题。
NSLog(@"%@",label);
可以为你提供输出的标签。它应该指出UILabel
本身
利用isKindOfClass:
来识别您正在更新的标签
答案 2 :(得分:1)
for (UILable *lblTemp in containerView.subviews){
if ([lblTemp isKindOfClass:[UILable class]] && lblTemp.tag==2){
// change the lbl color
break;
}
}
使用此代码检查;)