宽容他人,放过自己。

循环横向自动创建多个不同长度的label_自动换行

Posted on By anchoriteFili

循环创建多个不同长度的label.zip

752372-20150917155250148-787604365.png

示例代码

NSArray *arr = @[@"哈",@"哈哈",@"哈哈哈",@"哈哈哈哈",@"哈哈哈哈哈",@"哈哈哈哈哈哈",@"哈",@"哈哈",@"哈哈哈",@"哈哈哈哈",@"哈哈哈哈哈",@"哈哈哈哈哈哈",@"哈",@"哈哈",@"哈哈哈",@"哈哈哈哈",@"哈哈哈哈哈",@"哈哈哈哈哈哈",@"哈",@"哈哈",@"哈哈哈",@"哈哈哈哈",@"哈哈哈哈哈",@"哈哈哈哈哈哈",@"哈",@"哈哈",@"哈哈哈",@"哈哈哈哈",@"哈哈哈哈哈",@"哈哈哈哈哈哈",@"哈",@"哈哈",@"哈哈哈",@"哈哈哈哈",@"哈哈哈哈哈",@"哈哈哈哈哈哈",@"哈",@"哈哈",@"哈哈哈",@"哈哈哈哈",@"哈哈哈哈哈",@"哈哈哈哈哈哈",@"哈",@"哈哈",@"哈哈哈",@"哈哈哈哈",@"哈哈哈哈哈",@"哈哈哈哈哈哈",@"哈",@"哈哈",@"哈哈哈",@"哈哈哈哈",@"哈哈哈哈哈",@"哈哈哈哈哈哈",@"哈",@"哈哈",@"哈哈哈",@"哈哈哈哈",@"哈哈哈哈哈",@"哈哈哈哈哈哈",@"哈",@"哈哈",@"哈哈哈",@"哈哈哈哈",@"哈哈哈哈哈",@"哈哈哈哈哈哈",@"哈",@"哈哈",@"哈哈哈",@"哈哈哈哈",@"哈哈哈哈哈",@"哈哈哈哈哈哈",@"哈",@"哈哈",@"哈哈哈",@"哈哈哈哈",@"哈哈哈哈哈",@"哈哈哈哈哈哈",@"哈",@"哈哈",@"哈哈哈",@"哈哈哈哈",@"哈哈哈哈哈",@"哈哈哈哈哈哈",@"哈",@"哈哈",@"哈哈哈",@"哈哈哈哈",@"哈哈哈哈哈",@"哈哈哈哈哈哈",@"哈",@"哈哈",@"哈哈哈",@"哈哈哈哈",@"哈哈哈哈哈",@"哈哈哈哈哈哈",@"哈",@"哈哈",@"哈哈哈",@"哈哈哈哈",@"哈哈哈哈哈",@"哈哈哈哈哈哈",@"哈",@"哈哈",@"哈哈哈",@"哈哈哈哈",@"哈哈哈哈哈",@"哈哈哈哈哈哈",@"哈",@"哈哈",@"哈哈哈",@"哈哈哈哈",@"哈哈哈哈哈",@"哈哈哈哈哈哈",@"哈",@"哈哈",@"哈哈哈",@"哈哈哈哈",@"哈哈哈哈哈",@"哈哈哈哈哈哈"];
    
    CGFloat width = 0;
    CGFloat y = 0;
    
    for (int i = 0; i < arr.count; i ++) {
        
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor blueColor];
        [self.view addSubview:view];
        
        UILabel *labelOne = [[UILabel alloc] initWithFrame:CGRectMake(30+width, 10+y, 200, 30)];
        labelOne.backgroundColor = [UIColor redColor];
        labelOne.text = [arr objectAtIndex:i];
        [labelOne sizeToFit];
        [self.view addSubview:labelOne];
        
        view.frame = CGRectMake(labelOne.frame.origin.x-10, labelOne.frame.origin.y-5, labelOne.frame.size.width+20, labelOne.frame.size.height+10);
        
        width = labelOne.frame.origin.x+labelOne.frame.size.width;
        
        if (width >[UIScreen mainScreen].bounds.size.width) {
            
            width = 0;
            y = view.frame.origin.y+view.frame.size.height+5;
            
            labelOne.frame = CGRectMake(30+width, 10+y, 200, 30);
            [labelOne sizeToFit];
            
            view.frame = CGRectMake(labelOne.frame.origin.x-10, labelOne.frame.origin.y-5, labelOne.frame.size.width+20, labelOne.frame.size.height+10);
            width = labelOne.frame.origin.x+labelOne.frame.size.width;
        }
    }