iOS 動態顯示標籤
阿新 • • 發佈:2019-01-23
解決問題
1、根據標籤長度顯示;
2、多行顯示標籤;
程式碼片段:
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *arr = @[@"JAVA",@"C",@"C++",@"PHP",@"Object-C",@"Swift",@"JAVAWEB",@"C#",@"MYSQL"];
NSInteger x = 10;
NSInteger y = 100;
for (NSInteger i=0; i<arr.count; i++) {
NSString *str = [arr objectAtIndex:i];
CGSize size = [str sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16.0f]}];
if (x + size.width > self.view.frame.size.width-20) {
x = 10;
y = y + size.height+5; //5為兩行之間的高度間隔
}
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x, y, size.width , size.height)];
label.text = str;
label.font = [UIFont systemFontOfSize:16.0f];
label.backgroundColor = [UIColor orangeColor];
label.textColor = [UIColor whiteColor];
[self.view addSubview:label];
x = x + size.width +10; //10為兩個標籤之間的寬度間隔
}
}