【问题标题】:UITextView calculates height wrong if text input by copy paste如果通过复制粘贴输入文本,UITextView 计算高度错误
【发布时间】:2018-06-21 05:45:15
【问题描述】:
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

    let fixedWidth: CGFloat = textView.frame.size.width

    let newSize: CGSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))

    delegate.updateHeightTextView(height: newSize.height)

    return true
}

我在上面的函数中计算了 textview 的高度。 当我输入一些文本时效果很好,但是当我复制和粘贴文本时它不正确。

【问题讨论】:

  • 1.这是什么sizeThatFits 方法? 2.您的代码没有考虑建议的更改。请记住,shouldChangeTextIn 在文本视图实际更新之前被调用。 3. 你的代码即使在打字时也不能正常工作。
  • 观察 textView 的 text 属性并计算文本变化的大小您可以使用 RxCocoa 进行观察
  • @rmaddy 我更新了我的代码。
  • 当我输入时,newSize 返回正确,但当我粘贴文本时,它不正确
  • 你做的更新与我的cmets无关。

标签: ios swift textview


【解决方案1】:

在您的情况下,只要 TextView 的文本发生变化,您就必须计算 TextView 的高度。

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:nil];

- (void)textDidChange{
    //calculate the height here
}

UITextViewTextDidChangeNotification

【讨论】:

  • 当我输入第一个字符或首先粘贴一些文本时,我的 textViewDidchange 不会调用。所以我使用了: textViewDidChangeSelection(_ textView: UITextView) {} 成功了!
【解决方案2】:

您可以选择不同的方法来改变高度。

最简单的方法是设置:

textView.isScrollEnabled = false

或

取消选中

Scrolling Enabled 

故事板上 textview 的属性

这里文本视图的高度会根据内容而变化。

另一种方法是在 textView 委托方法中计算高度

func textViewDidChange(_ textView: UITextView) {

}

【讨论】:

  • 我使用了 func textViewDidChangeSelection(_ textView: UITextView) {} 因为我的 textViewDidChange() 在我输入第一个字符或首先粘贴一些文本时没有调用。我的 textview 放在 tableviewcell 中,所以我必须更新单元格高度
  • 设置委托并在单元类中使用委托方法。
【解决方案3】:

我找到了解决方案。而不是在文本视图中计算高度 - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text; 我计算在 - (void)textViewDidChangeSelection:(UITextView *)textView;

如果我计算 textViewDidChange 如果我首先键入第一个字符或粘贴一些文本,则不会调用它。

【讨论】:

    猜你喜欢
    • 2011-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    相关资源
    最近更新 更多