iOS for迴圈建立button,button的寬度根據上面的文字來自適應.
最近需要使用一個標籤頁,尋思自己寫一個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);}