【问题标题】:Get the exact size of UITextView with sizeWithAttribute使用 sizeWithAttribute 获取 UITextView 的确切大小
【发布时间】:2014-07-15 15:33:08
【问题描述】:

我有一个UISlider,它可以更改UITextView 的字体大小。在更改字体大小之前,我想检查我的UITextView 的高度是否会低于其视图容器的高度。问题是sizeToFitsizeWithAttribute 为相同的字体大小返回不同的高度。

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

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

对此有什么想法吗?

【问题讨论】:

  • 看起来self.photoDescription 包括文本周围的边距,而其他选项只是为您提供文本视图之外的文本。 (18 点字体不应该是 37.5 点高)。
  • 如何计算包括边距在内的高度?

标签: ios objective-c uitextview sizetofit


【解决方案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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-31
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多