很难确切地说出了什么问题...也许您(不小心)没有使用相同的字体?也许(不小心)没有使用完全相同的字符串?
无论如何,这似乎有点奇怪。
试试这个:
LabelHeightViewController.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface LabelHeightViewController : UIViewController
@end
NS_ASSUME_NONNULL_END
LabelHeightViewController.m
#import "LabelHeightViewController.h"
@interface LabelHeightViewController ()
@property (strong, nonatomic) UILabel *myLabel;
@property (strong, nonatomic) UIView *redView;
@end
@implementation LabelHeightViewController
- (void)viewDidLoad {
[super viewDidLoad];
_myLabel = [UILabel new];
_redView = [UIView new];
_myLabel.translatesAutoresizingMaskIntoConstraints = NO;
_redView.translatesAutoresizingMaskIntoConstraints = NO;
_myLabel.numberOfLines = 0;
_myLabel.text = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n\nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\n\n\nExcepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
UIFont *font = [UIFont fontWithName:@"Avenir-Book" size:16.0];
_myLabel.font = font;
// we're going to set the label width to 300
CGFloat w = 300.0;
// calculate the height
CGFloat h = [self getLabelHeight:_myLabel forWidth:w];
[self.view addSubview:_myLabel];
[self.view addSubview:_redView];
UILayoutGuide *g = self.view.layoutMarginsGuide;
[NSLayoutConstraint activateConstraints:@[
// constrain label Top: 40 / Leading: 12 / Width: w
[_myLabel.topAnchor constraintEqualToAnchor:g.topAnchor constant:40.0],
[_myLabel.leadingAnchor constraintEqualToAnchor:g.leadingAnchor constant:12.0],
[_myLabel.widthAnchor constraintEqualToConstant:w],
// constrain red view Top: label Top / Leading: label leading + 8
// Width: 20 / Height: h
[_redView.topAnchor constraintEqualToAnchor:_myLabel.topAnchor],
[_redView.leadingAnchor constraintEqualToAnchor:_myLabel.trailingAnchor constant:8.0],
[_redView.widthAnchor constraintEqualToConstant:20.0],
[_redView.heightAnchor constraintEqualToConstant:h],
]];
// so we can see the frames
_myLabel.backgroundColor = [UIColor yellowColor];
_redView.backgroundColor = [UIColor redColor];
}
-(CGFloat)getLabelHeight:(UILabel *)theLabel forWidth:(CGFloat)theWidth {
UIFont *descLabelFont = theLabel.font;
NSString *description = theLabel.text;
CGSize constraint = CGSizeMake(theWidth, CGFLOAT_MAX);
NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
CGSize boundingBox = [description boundingRectWithSize:constraint
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:descLabelFont}
context:context].size;
return ceil(boundingBox.height);
}
@end
结果:
注意事项:
红色视图的高度设置为返回的高度
-(CGFloat)getLabelHeight:(UILabel *)theLabel forWidth:(CGFloat)theWidth`
文本有两个换行符 - \n\n - 用于第一个“中断”和 3 个换行符 - \n\n\n - 用于第二个中断(用于演示)。