0

我需要计算 textView 的高度。

我正在使用两种不同的方式:

1.

 CGSize new_size= [self sizeThatFits:CGSizeMake(self.frame.size.width, MAXFLOAT)];
        CGFloat newHeight = new_size.height;
        CGRect new_frame = self.frame;
        new_frame.size.height = newHeight;
        [self setFrame:new_frame];

2.

 CGSize size = CGSizeMake(self.frame.size.width,MAXFLOAT);
    NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineBreakMode:NSLineBreakByCharWrapping];
    NSDictionary *attributes = @{ NSFontAttributeName: self.font, NSParagraphStyleAttributeName : paragraphStyle };

    CGRect frame = [self.text boundingRectWithSize:size
                                           options:(NSStringDrawingUsesLineFragmentOrigin)
                                        attributes:attributes
                                           context:context];

    CGFloat newHeight = frame.size.height;
    CGRect new_frame = self.frame;
    new_frame.size.height = newHeight;
    [self setFrame:new_frame];

有时它们返回相同的高度,有时第二种方法从第一种方法返回高度 <。

但始终第一种方法返回正确的高度!

第二种方法有什么问题?

编辑: 我注意到:当height < 59, 两个函数返回相同的东西时,当height >59第一种方法返回正确的高度时。第二个返回 59。

编辑: 似乎当我使用系统字体时:

[self setFont:[UIFont systemFontOfSize:15]]

上述两种方法都可以正常工作。

但是当我使用另一种字体时:

[self setFont:[UIFont fontWithName:@"Roboto-Light" size:15]]

那么第二种方法不能正常工作。

为什么会这样?

4

0 回答 0