程序员首页投稿(暂停使用,暂停投稿)iOS Developer

一个view中多个lable(或其他控件)中间的每个lable距

2016-08-07  本文已影响597人  AlexPei

- (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;
    }
    
}

上一篇下一篇

猜你喜欢

热点阅读