標籤:contex ati dict csdn cto 設定 文字 length cti
近期須要使用一個標籤頁,尋思自己寫一個demo.
標籤的大小依據上面的文字來自適應大小,須要依據後台返回的資料自己主動換行.沒有加入
NSArray *arr = @[@"無知",@"風雲變幻",@"施耐庵",@"唉",@"西門吹雪",@"呵呵噠",@"快看看",@"窿窿啦啦",@"一杆禽獸狙",@"合歡花",@"暴走大事件",@"非誠勿擾",@"呵呵呵"]; CGFloat w = 0;//儲存前一個button的寬以及前一個button距離螢幕邊緣的距離 CGFloat h = 200;//用來控制button距離父視圖的高 for (int i = 0; i < arr.count; i++) { UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem]; button.tag = 100 + i; button.backgroundColor = [UIColor greenColor]; [button addTarget:self action:@selector(handleClick:) forControlEvents:UIControlEventTouchUpInside]; [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal]; //依據計算文字的大小 NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:12]}; CGFloat length = [arr[i] boundingRectWithSize:CGSizeMake(320, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width; //為button賦值 [button setTitle:arr[i] forState:UIControlStateNormal]; //設定button的frame button.frame = CGRectMake(10 + w, h, length + 15 , 30); //當button的位置超出螢幕邊緣時換行 320 僅僅是button所在父視圖的寬度 if(10 + w + length + 15 > 320){ w = 0; //換行時將w置為0 h = h + button.frame.size.height + 10;//距離父視圖也變化 button.frame = CGRectMake(10 + w, h, length + 15, 30);//重設button的frame } w = button.frame.size.width + button.frame.origin.x; [self.view addSubview:button]; }點擊事件- (void)handleClick:(UIButton *)btn{ NSLog(@"%ld",btn.tag);}
iOS for迴圈建立button,button的寬度依據上面的文字來自適應.