根据服务器端返回的字符数组,展示字符串标签,需要涉及字符串长度处理以及字符串换行,字符串不够一行自动跳到第二行的逻辑

 NSArray * titleArray = @[@"#蓝色",@"#针织衫",@"#印花",@"#收腿裤",@"#豹纹",@"针织衫",@"周彦彤",@"JSON",@"123321",@"#蓝色",@"#针织衫",@"#印花",@"#收腿裤",@"#豹纹",@"针织衫",@"周彦彤",@"#蓝色",@"#针织衫",@"#印花",@"#收腿裤",@"#豹纹",@"针织衫",@"周彦彤",@"JSON",@"123321",@"#蓝色",@"#针织衫",@"#印花",@"#收腿裤",@"#豹纹",@"针织衫",@"周彦彤"];

    NSString * title = @"";

    UIFont * font = [UIFont systemFontOfSize:17];

    

    CGFloat wordWidth = 0;

    CGFloat nameLabelX = 0;

    CGFloat nameLabelY = 0;

    CGFloat width = 0;

    CGFloat section = 1;

    int j = 0;

    for (int i = 0; i < titleArray.count; i++) {

    

        title = [titleArray objectAtIndex:i];

        

        CGSize size = [title sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil]];

//这里如果需要支持ios7之前的相关使用这个方法:

// CGSize size = [title sizeWithFont:font constrainedToSize:CGSizeMake(UTIL_View_Width(self)-30, 16) lineBreakMode:NSLineBreakByWordWrapping];

 

        wordWidth = size.width + wordWidth;

 

        nameLabelX = (i == 0 ? 10 : 10 * (i + 1)) + (i == 0 ? 0: wordWidth - size.width) ;

        

        if (nameLabelX + size.width > [UIScreen mainScreen].bounds.size.width || isExchange == YES) {

            width = size.width + width;

            nameLabelX = (j == 0 ? 10 : 10 * (j + 1)) + (j == 0 ? 0: width - size.width);

            j++;

            

            nameLabelY = 100 + size.height *section  + 10 * section;

            if(nameLabelX + size.width > [UIScreen mainScreen].bounds.size.width){

                width = 0;

                width = size.width + width;

                j= 0;

                section = section + 1;

                

                nameLabelX = (j == 0 ? 10 : 10 * (j + 1)) + (j == 0 ? 0: width - size.width);

                j++;

                

                nameLabelY = 100 + size.height *section  + 10 * section;

            }

            isExchange = YES;

        }else if (nameLabelX + size.width <= [UIScreen mainScreen].bounds.size.width && isExchange == NO){

            nameLabelX = nameLabelX;

            nameLabelY = 100;

 

        }

        UILabel * nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(nameLabelX , nameLabelY, size.width, size.height)];

        nameLabel.text = title;

        nameLabel.backgroundColor = [UIColor redColor];

        NSLog(@"%f",nameLabel.frame.origin.y);

        [self.view addSubview:nameLabel];

    }

 

posted @ 2015-08-10 14:54  那个顾客  阅读(245)  评论(0编辑  收藏  举报