最近有个需求要求写一个这样的效果。最开始打算自己写。然后整理了一下思路,并没有实现,脑瓜都快炸了。看了一下网上其他人的实现。感觉不是自己想要的。然后回家想了一个晚上。早上来终于搞定了。
//历史纪录标签
CGFloat lineHeight = 0;//记录换行的y值
CGFloat marginY = 0;//累加每一行的行距
self.arraySearch = [self readFromFile];//数据原
for(NSInteger i=0;i<self.arraySearch.count;i++){
UIButton *tempBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[tempBtn setTitle:self.arraySearch[i] forState:UIControlStateNormal];
tempBtn.backgroundColor = [UIColor whiteColor];
[tempBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
CGFloat y = self.labelTitle.zlMaxY+20;//初始Y值
CGFloat x = 20+_btnframe.zlMaxX;//累加的x值
//如果换行了,就用换行之后的y值
if(lineHeight != 0){
y = lineHeight;
}
//设置按钮的frame
tempBtn.frame = BQAdaptationFrame(x, y, 40, 40);
//记录上一个按钮的frame
_btnframe = tempBtn;
tempBtn.titleLabel.font = [UIFont systemFontOfSize:25*BQAdaptationWidth()];
tempBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
tempBtn.layer.borderWidth = 0.5;
[tempBtn sizeToFit];//自适应宽高
//设置按钮自适应宽高之后重新设置frame
CGRect frame = tempBtn.frame;
frame.size.width = frame.size.width + 20 * BQAdaptationWidth();
tempBtn.frame = frame;
//判断是x值是否超出屏幕宽度
if(tempBtn.zlMaxX > IPHONE_WIDTH - 20){
//重新设置初始x值
frame.origin.x = 20*BQAdaptationWidth();
//记录换行y
lineHeight = self.labelTitle.zlMaxY+80+marginY;
//累加行距
marginY += 60;
//设置换行之后的y值
frame.origin.y = lineHeight * BQAdaptationWidth();
//设置frame
tempBtn.frame = frame;
}
[self.backView addSubview:tempBtn];
}