UIlabel排列简单视图

2018-08-30  本文已影响10人  lizhi_boy
image.png

简单的逻辑代码

- (void)viewDidLoad {
    [super viewDidLoad];


    CGFloat leftMargin = 10;
    CGFloat topMargin = 20;
    CGFloat item_space = 10;
    CGFloat width_index = 0;//累加label的宽度(不包含space)
    CGFloat label_width = 0;
    CGFloat label_left = 0;
    CGFloat label_top = topMargin;
    CGFloat label_height = 30;
    
    width_index = 2*leftMargin;//默认
    BOOL isReturn = NO;
    
    NSArray *titles = @[@"34343434343",@"66666666666666666666666666",@"66666666666666666666666666",@"66666666666666666666666666",@"66666666655555555555",@"tyty",@"777777777",@"655575buytrjgfhfgdh"];
       for (int i = 0; i < titles.count; i++) {
        
        UILabel *testLb = [UILabel new];
        testLb.userInteractionEnabled = YES;
        testLb.tag = 100+i;
        testLb.textAlignment = NSTextAlignmentCenter;
//        testLb.backgroundColor = [UIColor whiteColor];
        testLb.text =titles[i];
        testLb.textColor = [UIColor blackColor];
        label_width = [self widthFromText:titles[i] fontSize:20] + item_space;
        
        //过滤长度大于屏幕一半的label
        if (label_width > (ScreenWidth-20)/2) {
            label_width = (ScreenWidth-20)/2-10;
        }
          //换行操作
          width_index += label_width;
        
        if (width_index > ScreenWidth) {
            isReturn = YES;
            width_index = 2*leftMargin + label_width;
        }else{
            isReturn = NO;
        }
        
        UILabel *lastLb = [self viewWithTag:100+i-1];
        
        if (isReturn) {
            
            label_left = leftMargin;
            label_top = CGRectGetMaxY(lastLb.frame) + topMargin;
            label_left = leftMargin;
            
        }else{
            
            label_left = i==0 ? leftMargin : CGRectGetMaxX(lastLb.frame) + item_space;
            
        }
        
        testLb.frame = CGRectMake(label_left,label_top,label_width,label_height);
        [self.keywordView addSubview:testLb];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickKeyword:)];
        [testLb addGestureRecognizer:tap];
        
    }
}

-(void)LabelClick:(UITapGestureRecognizer *)sender{
    
    UILabel *lb = (UILabel *)sender.view;
    NSLog(@"你点击了%ld",lb.tag-100);
}

//计算UIlabel的宽度
-(CGFloat)widthFromText:(NSString *)text fontSize:(CGFloat)fontSize{
    
    CGSize titleSize = [text sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:CGSizeMake(MAXFLOAT, 30)];
    return titleSize.width;
    
}
上一篇下一篇

猜你喜欢

热点阅读