我使用这段代码创建了多个标签,
.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;
}并使用以下代码设置特定表中的背景色和文本颜色。
- (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];
}它将很好地更新标签的背景,但是当我使用这段代码更新文本颜色时,它将显示如下错误
由于“NSInvalidArgumentException”异常终止应用程序,原因:'-UIView setTextColor::未识别的选择器发送到实例0xbaa3b30‘
有设置文本颜色的方法吗?请帮帮忙。
发布于 2013-07-23 12:52:40
containerView视图,:2;
check容器视图只有一个视图,它是带有标签2的标签。可能是其他视图与标签2一起设置的,并且可能导致了问题。
NSLog(@"%@",label);可以给出这里的标签给出的输出,.It应该指出UILabel本身
使用isKindOfClass:来识别它是您正在更新的标签
发布于 2013-07-23 12:59:55
从1而不是0开始标签标记,因为默认情况下,所有视图的标记值为0。
lbl.tag = i+1; 因为
UILabel *label = (UILabel *)[containerView viewWithTag:0]; 它将返回containerView本身,而UIView不具有textColor属性:P
发布于 2013-07-23 13:04:51
for (UILable *lblTemp in containerView.subviews){
if ([lblTemp isKindOfClass:[UILable class]] && lblTemp.tag==2){
// change the lbl color
break;
}
}(使用此代码进行检查;)
https://stackoverflow.com/questions/17810600
复制相似问题