绘制长度不定可自动换行的标签

#pragma mark - 尝试绘制自动换行的类型标签label

- (void)createTypeBtnsView{
    
    tagView = [[UIView alloc]initWithFrame:CGRectMake(10, 45 + 300*self.model.imagesArray.count, [DMDevceManager screenWidth]-20, 10)];
    CGFloat positionX = 0.0;
    CGFloat positionY = 0.0;
    CGFloat bgViewWidth = [DMDevceManager screenWidth]-20;
    
    UIFont *btnTitleFont = [UIFont systemFontOfSize:13];
    
    //如果有图片作为边框,使用注释
//    UIImage *selImage = [UIImage imageNamed:@"greenCir1"];
//    UIImage *norImage = [UIImage imageNamed:@"grayCir2"];
    
//    CGFloat left = selImage.size.width/4;
//    CGFloat top = selImage.size.height/4;
    
    for(int i = 0;i<self.model.typesArray.count;i++)
    {
        CGFloat btnWidth = [DMUtils textWidth:self.model.typesArray[i] Font:btnTitleFont height:25];
        
        if(positionX + btnWidth > bgViewWidth){
            positionX = 0;
            positionY += 30;
        }
        
        UIButton *btn = [DMUITool createButtonWithFrame:CGRectMake(positionX, positionY, btnWidth, 25) title:self.model.typesArray[i] target:self action:@selector(typeBtnClick:) tag:i+30000];
        btn.titleLabel.font = btnTitleFont;
        
        btn.backgroundColor = Color(103, 206, 249);
        btn.layer.masksToBounds = YES;
        btn.userInteractionEnabled = YES;
        btn.layer.cornerRadius = 12;
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

        
        positionX += (btnWidth+5);
        //如果有图片作为边框,从4分之1处拉伸
//        [btn setBackgroundImage:[selImage stretchableImageWithLeftCapWidth:left topCapHeight:top] forState:UIControlStateSelected];
//        [btn setBackgroundImage:[norImage stretchableImageWithLeftCapWidth:left topCapHeight:top] forState:UIControlStateNormal];
        
        [tagView addSubview:btn];
        
    }
/*
 *获取文字所占宽度
 *@param text 文本内容,计算式包括了换行空格等
 *@param font 字体
 *@param height:指定高度下计算,若不设限使用CGFLOAT_MAX
 */
+ (CGFloat)textWidth:(NSString *)text Font:(UIFont *)font height:(CGFloat)height
{
    if(![DMDevceManager isiOS7]){
        return [text sizeWithFont:font constrainedToSize:CGSizeMake(MAXFLOAT, height) lineBreakMode:NSLineBreakByCharWrapping].width;
        
    }else{
    
//        NSDictionary *attribute = @{NSFontAttributeName:font};
//        CGSize retSize = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, height) options:   NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
//        
//        return retSize.width;
        
        if(text.length <= 0){
            return 0;
        }
        
    UITextView *textView = APPDELEGATE.textView;
    textView.text = text;
    textView.font = font;
    CGSize size = [textView sizeThatFits:CGSizeMake(CGFLOAT_MAX, height)];
    return size.width;
        
    }
}



效果如图:

绘制长度不定可自动换行的标签_第1张图片

你可能感兴趣的:(ios,自动换行,标签,适配)