1

我有一个UISlider改变 a 的字体大小的 a UITextView。在更改字体大小之前,我想检查一下我的高度UITextView是否会低于其视图容器的高度。问题在于,sizeToFit并且sizeWithAttribute正在为相同的字体大小返回不同的高度。

为此,我正在尝试UITextView使用自定义 fontSize 来获得我的高度,但我无法找到这样做的方法,并且不明白为什么我这样做时没有得到相同的高度:

self.photoDescription.text = @"Test"
self.photoDescription.font = [self.photoDescription.font fontWithSize:18];
[self.photoDescription sizeToFit];
NSLog(@"real height %f", self.photoDescription.frame.size.height); 
//getting : 37.5

和:

NSLog(@"calculated height %f", [self.photoDescription.text sizeWithAttributes:@{NSFontAttributeName:[self.photoDescription.font fontWithSize:18]}].height);
//getting: 20.97

同样的事情:

CGRect textRect = [self.photoDescription.text boundingRectWithSize:CGSizeMake(320, 300)
                                             options:NSStringDrawingUsesLineFragmentOrigin
                                          attributes:@{NSFontAttributeName:[self.photoDescription.font fontWithSize:18]}
                                             context:nil];

CGSize size = textRect.size;
NSLog(@"height %f", size.height);
// getting : 20.97

对此有什么想法吗?

4

1 回答 1

1

我终于用 Jordan Montel 解决方案找到了我的问题的答案: iOS7 UITextView contentsize.height Alternative

我用他的函数来获取宽度:

- (CGFloat)textViewHeightForAttributedText:(NSAttributedString *)text andWidth:(CGFloat)width
{
    UITextView *textView = [[UITextView alloc] init];
    [textView setAttributedText:text];
    CGSize size = [textView sizeThatFits:CGSizeMake(width, FLT_MAX)];
    return size.height;
}
于 2014-05-27T15:36:03.073 回答