- 一個(gè)view鐘多個(gè)一樣的空間例如lable,txtField,或者其他控件一樣的控件,屏幕最兩邊的控件距離屏幕距離一定,中間的控件兩兩之間的距離相等.通過(guò)一個(gè)簡(jiǎn)單的封裝方法來(lái)搞定.
- 之前用Masonry來(lái)約束,雖然效果得到了,但是還是有警告,看著不爽啊,所以干脆直接計(jì)算fram進(jìn)行約束.也不難
- 具體方法如下:
- (void)viewDidLoad {
[super viewDidLoad];
[self setUI];
}
-(void)setUI{
//下面注釋的方法跟最下面封裝的方法最終效果一樣
// CGFloat leftDistance = 15.0; //最左邊控件距離屏幕左邊的距離
// CGFloat lblWidth = 40.0; //控件寬度
// CGFloat lblHeight = 21.0; //控件高度,控件y坐標(biāo)我設(shè)置成了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];
}
/**
* 設(shè)置中間部分控件兩兩之間距離相等
*
* @param arrTitles label的名字?jǐn)?shù)組
* @param lDistance 最左邊控件距離屏幕左邊的距離
* @param width 控件寬度
* @param height 控件高度
* @param y 控件y坐標(biāo)
*/
-(void)setLablesWithArrOfTitle:(NSArray<NSString *> *)arrTitles andLeftDistance:(CGFloat)lDistance andItWidth:(CGFloat)width andItHeight:(CGFloat)height andYcoordinate:(CGFloat) y{
//獲取屏幕寬度
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
//計(jì)算中間兩個(gè)lable之間的距離
CGFloat margin = (screenWidth - 2*lDistance - width*arrTitles.count) / (arrTitles.count - 1);
//緩存tempLable用于存儲(chǔ)當(dāng)前創(chuàng)建出來(lái)的lable,目的是當(dāng)創(chuàng)建下一個(gè)lable的時(shí)候通過(guò)CGRectGetMaxX(tempLabel.frame)這個(gè)方法來(lái)獲取上一個(gè)lable的最大x坐標(biāo)maxX加上margin就得到了下一個(gè)lable的x坐標(biāo),以此類推即可.
UILabel * tempLabel = [UILabel new];
for (int i = 0; i< arrTitles.count; i++) {
//由于第一個(gè)lable比較特殊,他距離屏幕左邊與右邊的lable距離不相等,所以在此進(jìn)行判斷過(guò)濾.
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個(gè)點(diǎn), '二'與'三'距離兩邊的lable都相等,'四'與'一'距離屏幕右邊與左邊都相等 = 15
-