创建label:
.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];
}
背景颜色实现更新,但是文本颜色更新会报错:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView setTextColor:]: unrecognized selector sent to instance 0xbaa3b30'
不知道怎么设置?谢谢
异常提示信息很清楚的说明了出错的原因。
主要的问题出在:你使用viewWithTag拿到的 UI并非是UILabel对象,而是UIView。这个从报错的信息中可以看出
[UIView setTextColor:]: unrecognized selector sent to instance
所以根据上面的分析,问题的关键在于,在你的updateLabelMethod中
UILabel *label = (UILabel *)[containerView viewWithTag:2];
你所拿到实际上并非UIlabel对象。出现这个的原因很有可能是某个UIView 和 UILabel同时设置了tag的值为2, 在使用viewWithTag查找时,首先找到的是那个UIView 就返回给了你,当你给UIview 发送setTextColor消息时肯定会报错的。