【问题标题】:UITextView height is wrong in iOS 9iOS 9 中的 UITextView 高度错误
【发布时间】:2016-05-06 10:21:30
【问题描述】:

我有一个UITextView,它会根据其内容调整大小。但是 iOS9 给出了错误的高度值。我试过 UITextView height according to content is wrong in iOS 9 。但这并不能解决我的问题。我的 textview 在表格视图单元格中,并且我的单元格高度根据 textview 高度而变化。

newSize = [_cell.detailedTextView sizeThatFits:CGSizeMake(CGRectGetWidth(_cell.detailedTextView.bounds), CGRectGetHeight(_cell.detailedTextView.bounds))];

【问题讨论】:

    标签: ios objective-c uitableview uitextview


    【解决方案1】:

    请试试这个。可能对你有帮助

      + (CGFloat)gettextViewHeight:(UITextView*)textView
      {
         CGSize constraint = CGSizeMake(textView.frame.size.width, 20000.0f);
         CGSize size;
    
          NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
          CGSize boundingBox = [textView.text boundingRectWithSize:constraint
                                                  options:NSStringDrawingUsesLineFragmentOrigin
                                               attributes:@{NSFontAttributeName:textView.font}
                                                  context:context].size;
    
          size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));
    
          return size.height;
      }
    

    【讨论】:

    • 缩小了,但还有一点空间。
    • 你有多少空间?
    • 额外大约 50 分。仅当 textview 中的行数超过 10 行时才会发生这种情况
    • 但是行数少了会影响其他单元格吗?
    • 我检查了一下,发现问题只出现在 iPhone 6 和 iPhone 6 Plus,而不是 iPhone 5s 和 iOS 9
    【解决方案2】:

    问题是 boundingRect 是针对大写高度计算的,而不是针对字体上升器。这会导致整行不出现。

    一旦你考虑到它会正确显示:

    func height(of string: String, in textView: UITextView) -> CGFloat 
    {
        let font = textView.font ?? UIFont.preferredFont(forTextStyle: .headline)
        let width = textView.bounds.size.width - 2.0 * textView.textContainer.lineFragmentPadding
        let size = CGSize(width: width,
                          height: CGFloat.greatestFiniteMagnitude)
        let height = string.boundingRect(with: size,
                                         options: [.usesLineFragmentOrigin, .usesFontLeading],
                                         attributes: [NSAttributedString.Key.font: font],
                                         context: nil).size.height
        let insets = textView.textContainerInset.top + textView.textContainerInset.bottom
        let diff = ceil(font.ascender - font.capHeight)
        return height + insets + diff
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-26
      • 2013-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多