UILabel自适应内容高度总结

来源:互联网 发布:淘宝打印订单 编辑:程序博客网 时间:2024/06/09 05:57

自适应内容高度现在总结两种方法

方法一:  其实就是先按着自己想要的效果给弄出来,然后根据宽度得到这个控件的cgsize

    NSString * stringStr =@"我是内容我是内容我是内容我是内容我是内容我是内容..";

    NSMutableAttributedString  * attstr = [[NSMutableAttributedStringalloc] init];

    //label图片文字混排

    NSTextAttachment * textAttach=[[NSTextAttachmentalloc]init];

    textAttach.image=[UIImageimageNamed:@"abstract"];

    textAttach.bounds=CGRectMake(0,0, 42, 20);

    NSAttributedString *strA = [NSAttributedStringattributedStringWithAttachment:textAttach];

    [attstr appendAttributedString:strA];

    [attstr appendAttributedString:[[NSAttributedStringalloc] initWithString:stringStr]];

    //label行间距

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStylealloc]init];

    [paragraphStylesetLineSpacing:10];

    [attstraddAttribute:NSParagraphStyleAttributeNamevalue:paragraphStyle range:NSMakeRange(0, [stringStrlength])];

    

   UILabel * lbzy = [[UILabelalloc]init];

    lbzy.attributedText=attstr;

    lbzy.lineBreakMode=NSLineBreakByWordWrapping;

    lbzy.numberOfLines=0;

    lbzy.font=[UIFontsystemFontOfSize:13];

    //调节高度

   CGSize size = CGSizeMake(KWidth-20,MAXFLOAT);

   CGSize labelSize = [lbzy sizeThatFits:size];

    lbzy.frame =CGRectMake(10,10,KWidth-20,labelSize.height);//设置labelframe


方法二:   这个是根据宽度得到内容的cgsize,然后赋值给label

    //标题

   NSString * stringStr = [@"我是标题"stringByTrimmingCharactersInSet:whitespace];

    CGSize size=[stringStrsizeWithFontCompatible:[UIFontsystemFontOfSize:14]forWidth:(screenW-100)lineBreakMode:NSLineBreakByWordWrapping];

   _newsTitle.frame=CGRectMake(91,0,screenW-100,size.height);

    _newsTitle.lineBreakMode=NSLineBreakByWordWrapping;

    _newsTitle.numberOfLines=0;

   _newsTitle.text=stringStr;

   

   

 NSDictionary *dictionaryAttributes =@{NSFontAttributeName:font,};

       CGRect stringRect = [selfboundingRectWithSize:CGSizeMake(width,MAXFLOAT)

                                              options:NSStringDrawingUsesLineFragmentOrigin

                                           attributes:dictionaryAttributes

                                              context:nil];


 


0 0
原创粉丝点击