iOS label自适应宽度 左端对齐 自动换行

        UILabel * label = [[UILabel alloc]initWithFrame:cell.bounds];

        label.textAlignment = NSTextAlignmentLeft;

        label.numberOfLines =0;

        label.backgroundColor = [UIColor redColor];


     

        label.text = [_dic objectForKey:@"course"];

        //iOS 6.0如下

        CGSize size = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(self.view.frame.size.width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];

        label.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y, size.width, size.height);

        //iOS 7.0后如下


 CGRect rect = [label.text boundingRectWithSize:CGSizeMake(self.view.frame.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:label.font} context:nil];

        

        label.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y, rect.size.width, rect.size.height);




        [cell addSubview:label];

你可能感兴趣的:(iOS label自适应宽度 左端对齐 自动换行)