【问题标题】:Swift - Rotated UITextView autosize problemSwift - 旋转的 UITextView 自动调整大小问题
【发布时间】:2018-12-22 02:58:56
【问题描述】:

我使用此功能使 UITextView 在键入时自动适应文本内容。当 TextView 水平时它工作正常,但在 TextView 旋转时不能正常工作。有什么想法可以解决吗?

func textViewDidChange(_ textView: UITextView) {

    let newSize = textView.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
    textView.frame = CGRect(origin: textView.frame.origin, size: newSize)

}

【问题讨论】:

  • 你是如何旋转文本视图的?使用transform?
  • 是的,UIRotationGestureRecognizer 和变换@Sweeper

标签: ios iphone swift text uitextview


【解决方案1】:

根据docs

当此属性的值不是恒等变换时,frame 属性中的值未定义,应被忽略。

我认为这可能是您的代码不起作用的原因 - 在您应用转换后,frame 未定义。

在设置框架之前尝试将转换设置回身份:

let transform = textView.transform
textView.transform = .identity
let newSize = textView.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
textView.frame = CGRect(origin: textView.frame.origin, size: newSize)
textView.transform = transform

【讨论】:

    【解决方案2】:

    我看到 UITextView 有时不能很好地处理转换。 将 UITextView 包装在 UIView 中。将 UITextView 的 top、leading、bottom 和 trailing 设置为 UIView。在 UIView 上执行所有转换。你应该很高兴。

    【讨论】:

      【解决方案3】:

      我有同样的问题,我看到了这个问题,之后我就这样解决了;

      extension UITextView {
        func calculateSize() {
          let currentTransform = transform
          transform = .identity
          
          let currentCenter = center
          let fixedWidth: CGFloat = font == nil ? 300 : text.widthOfString(usingFont: font!) + 16 // 300 for the worst case scenario and 16 is for leading and trailing spaces for content
          sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
          
          let newSize = sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
          var newFrame = frame
          newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
          
          frame = newFrame
          center = currentCenter
          transform = currentTransform
          
          layoutIfNeeded()
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-13
        • 2014-01-18
        • 2018-05-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多