ios中根据文本设置label高度

UILabel * label = [[UILabel alloc] init];    
    NSString * text = @"hellohellohellohellohellohellohellohellohellohellohellohello ";    
    label.text = text;
    [label setNumberOfLines:0];
    UIFont *font = [UIFont fontWithName:@"Arial" size:14];    
    //设置字体    
    label.font = font;    
    CGSize size = CGSizeMake(300, 20000.0f);
    size = [text sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByCharWrapping];
    [label setFrame:CGRectMake(10, 0, size.width, size.height)];
   [self.view addSubview:label];

lineBreakMode:设置标签文字过长时的显示方式。 
label.lineBreakMode = NSLineBreakByCharWrapping;以字符为显示单位显示,后面部分省略不显示。 
label.lineBreakMode = NSLineBreakByClipping;剪切与文本宽度相同的内容长度,后半部分被删除。 
label.lineBreakMode = NSLineBreakByTruncatingHead;前面部分文字以……方式省略,显示尾部文字内容。 
label.lineBreakMode = NSLineBreakByTruncatingMiddle;中间的内容以……方式省略,显示头尾的文字内容。 
label.lineBreakMode = NSLineBreakByTruncatingTail;结尾部分的内容以……方式省略,显示头的文字内容。 
label.lineBreakMode = NSLineBreakByWordWrapping;以单词为显示单位显示,后面部分省略不显示。

http://www.xue5.com/Mobile/iOS/673562.html


这是网上的代码,可以正常运行。但还遇到一个问题,就是这里的label是动态生成的,如果对于view中一个拖出来的label然后在controller中连接一个对应的属性,这个label的setFrame始终无效,这时可以点到size inspector中,找到constraints中的height equals,点击后面的齿轮图案,选择select and edit,在height constraints中将Priority的值设置的小一些即可。

warn
作者:心亦
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/szhx/p/3219336.html