京东 qq 自定义tabbar控件均分
- 代码如下
//ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor orangeColor];
[self setLablesWithArrOfTitle:@[@"one",@"哈哈",@"你妹的",@"我去"] andLeftDistance:15 andItHeight:21 andYcoordinate:255 andDestiView:self.view];
[self setLablesWithArrOfTitle:@[@"one",@"哈哈",@"你妹的",@"我去"] andLeftDistance:15 andItWidth:44 andItHeight:21 andYcoordinate:155 andDestiView:self.view];
}
对应方法
- 为了对比明显将控制器背景色,以及控件背景色都设置上了不同的颜色以便于观看
自动计算label的宽度
/**
* 设置中间部分控件两两之间距离相等,两端控件距离两侧为中间控件的一半
* 根据lDis计算label宽度
* @param arrTitles label的名字数组
* @param lDistance 最左边控件距离屏幕左边的距离
* @param height 控件高度
* @param y 控件y坐标
*/
-(void)setLablesWithArrOfTitle:(NSArray<NSString *> *)arrTitles andLeftDistance:(CGFloat)lDistance andItHeight:(CGFloat)height andYcoordinate:(CGFloat) y andDestiView:(UIView *)destiView{
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
CGFloat margin = 2 * lDistance;
CGFloat width = (screenWidth - arrTitles.count * 2 * lDistance)/arrTitles.count;
UILabel * tempLabel = [UILabel new];
for (int i = 0; i< arrTitles.count; i++) {
if (i == 0) {
UILabel * lbl = [[UILabel alloc] initWithFrame:CGRectMake(lDistance, y, width, height)];
lbl.backgroundColor = [UIColor whiteColor];
lbl.textAlignment = NSTextAlignmentCenter;
lbl.text = arrTitles[0];
[destiView addSubview:lbl];
tempLabel = lbl;
continue;
}
UILabel * lbl = [[UILabel alloc] initWithFrame:CGRectMake((CGRectGetMaxX(tempLabel.frame)+margin), y, width, height)];
lbl.textAlignment = NSTextAlignmentCenter;
lbl.backgroundColor = [UIColor whiteColor];
lbl.text = arrTitles[i];
[destiView addSubview:lbl];
tempLabel = lbl;
}
}
自定义label的宽度
/**
* 设置中间部分控件两两之间距离相等
* 自定义label宽度
* @param arrTitles label的名字数组
* @param lDistance 最左边控件距离屏幕左边的距离
* @param width 控件宽度
* @param height 控件高度
* @param y 控件y坐标
*/
-(void)setLablesWithArrOfTitle:(NSArray<NSString *> *)arrTitles andLeftDistance:(CGFloat)lDistance andItWidth:(CGFloat)width andItHeight:(CGFloat)height andYcoordinate:(CGFloat) y andDestiView:(UIView *)destiView{
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
CGFloat margin = (screenWidth - 2*lDistance - width*arrTitles.count) / (arrTitles.count - 1);
UILabel * tempLabel = [UILabel new];
for (int i = 0; i< arrTitles.count; i++) {
if (i == 0) {
UILabel * lbl = [[UILabel alloc] initWithFrame:CGRectMake(lDistance, y, width, height)];
lbl.backgroundColor = [UIColor whiteColor];
lbl.textAlignment = NSTextAlignmentCenter;
lbl.text = arrTitles[0];
[destiView addSubview:lbl];
tempLabel = lbl;
continue;
}
UILabel * lbl = [[UILabel alloc] initWithFrame:CGRectMake((CGRectGetMaxX(tempLabel.frame)+margin), y, width, height)];
lbl.backgroundColor = [UIColor whiteColor];
lbl.textAlignment = NSTextAlignmentCenter;
lbl.text = arrTitles[i];
[destiView addSubview:lbl];
tempLabel = lbl;
}
}
最终效果
- 第一行是自定义控件宽度
- 第二行是自动计算控件宽度 根据自己需求调用即可
- 方法内部稍加修改就可以作为创建UIButton,UIImageView,UITxtField等等.