1.- (CGSize)sizeWithAttributes:(NSDictionary *)attrs;
当文本内容的宽不超过屏幕的宽时,就可以确定Label的宽,否则,只会显示出一行,超出的内容不会显示出来。
self.myLabel = [[UILabel alloc]init];
[self.view addSubview:self.myLabel];
self.myLabel.text = @"iOS根据文字字数动态确定Label宽高";
self.myLabel.textColor = [UIColor redColor];
UIFont *font = [UIFont fontWithName:@"HelveticaNeue" size:24.0f];
self.myLabel.font = font;
根据字体得到NSString的尺寸
CGSize size = [self.myLabel.text sizeWithAttributes:@{NSFontAttributeName:font}];
self.myLabel.frame = CGRectMake(0, 100, size.width, size.height);
self.myLabel.numberOfLines = 0;
// self.myLabel.lineBreakMode = NSLineBreakByWordWrapping;
CGRect tmpRect = [ self . myLabel . text boundingRectWithSize : CGSizeMake (200, MAXFLOAT ) options : NSStringDrawingUsesLineFragmentOrigin attributes :[ NSDictionary dictionaryWithObjectsAndKeys :font, NSFontAttributeName , nil ] context : nil ];self.myLabel.frame = CGRectMake(0, 100, tmpRect.size.width,tmpRect.size.height);