- 一个view钟多个一样的空间例如lable,txtField,或者其他控件一样的控件,屏幕最两边的控件距离屏幕距离一定,中间的控件两两之间的距离相等.通过一个简单的封装方法来搞定.
- 之前用Masonry来约束,虽然效果得到了,但是还是有警告,看着不爽啊,所以干脆直接计算fram进行约束.也不难
- 具体方法如下:
- (void)viewDidLoad {
[super viewDidLoad];
[self setUI];
}
-(void)setUI{
//下面注释的方法跟最下面封装的方法最终效果一样
// CGFloat leftDistance = 15.0; //最左边控件距离屏幕左边的距离
// CGFloat lblWidth = 40.0; //控件宽度
// CGFloat lblHeight = 21.0; //控件高度,控件y坐标我设置成了20
//
// CGFloat margin = (kScreenW - 30 - 160) / 3.0;
// UILabel * lblOne = [[UILabel alloc] initWithFrame:CGRectMake(15, 20, 40, 21)];
// lblOne.textAlignment = NSTextAlignmentCenter;
// [self.view addSubview:lblOne];
// lblOne.text = @"one";
//
// UILabel * lblTwo = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(lblOne.frame)+margin, 20, 40, 21)];
// lblTwo.textAlignment = NSTextAlignmentCenter;
// [self.view addSubview:lblTwo];
// lblTwo.text = @"two";
//
// UILabel * lblThree = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(lblTwo.frame)+margin, 20, 40, 21)];
// lblThree.textAlignment = NSTextAlignmentCenter;
// [self.view addSubview:lblThree];
// lblThree.text = @"three";
//
// UILabel * lblFour = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(lblThree.frame)+margin, 20, 40, 21)];
// lblFour.textAlignment = NSTextAlignmentCenter;
// [self.view addSubview:lblFour];
// lblFour.text = @"four";
[self setLablesWithArrOfTitle:@[@"一",@"二",@"三",@"四"] andLeftDistance:15.0 andItWidth:40 andItHeight:21 andYcoordinate:20];
}
/**
* 设置中间部分控件两两之间距离相等
*
* @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{
//获取屏幕宽度
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
//计算中间两个lable之间的距离
CGFloat margin = (screenWidth - 2*lDistance - width*arrTitles.count) / (arrTitles.count - 1);
//缓存tempLable用于存储当前创建出来的lable,目的是当创建下一个lable的时候通过CGRectGetMaxX(tempLabel.frame)这个方法来获取上一个lable的最大x坐标maxX加上margin就得到了下一个lable的x坐标,以此类推即可.
UILabel * tempLabel = [UILabel new];
for (int i = 0; i< arrTitles.count; i++) {
//由于第一个lable比较特殊,他距离屏幕左边与右边的lable距离不相等,所以在此进行判断过滤.
if (i == 0) {
UILabel * lbl = [[UILabel alloc] initWithFrame:CGRectMake(lDistance, y, width, height)];
lbl.textAlignment = NSTextAlignmentCenter;
lbl.text = arrTitles[0];
[self.view addSubview:lbl];
tempLabel = lbl;
continue;
}
UILabel * lbl = [[UILabel alloc] initWithFrame:CGRectMake((CGRectGetMaxX(tempLabel.frame)+margin), y, width, height)];
lbl.textAlignment = NSTextAlignmentCenter;
lbl.text = arrTitles[i];
[self.view addSubview:lbl];
tempLabel = lbl;
}
}
- 最终的效果是这样
-
'一'距离左边15个点, '二'与'三'距离两边的lable都相等,'四'与'一'距离屏幕右边与左边都相等 = 15
-