創建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消息時肯定會報錯的。