简体   繁体   English

Swift - 旋转的 UITextView 自动调整大小问题

[英]Swift - Rotated UITextView autosize problem

I use this function to make UITextView auto fit text content when typing.我使用此功能使 UITextView 在键入时自动适应文本内容。 It works fine when the TextView is horizontal but does not work correctly when TextView is rotated.当 TextView 水平时它工作正常但当 TextView 旋转时它不能正常工作。 Any ideas how it can be fixed?任何想法如何解决?

func textViewDidChange(_ textView: UITextView) {

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

}

According to the docs :根据文档

When the value of this property is anything other than the identity transform, the value in the frame property is undefined and should be ignored.当此属性的值不是恒等变换时, frame属性中的值是未定义的,应该被忽略。

I think that might be why your code doesn't work - frame is undefined after you have applied a transform.我认为这可能是您的代码不起作用的原因 - 应用转换后frame未定义。

Try setting the transform back to identity before setting the 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

I have seen UITextView sometimes does not play good with transformations.我看到 UITextView 有时不能很好地处理转换。 Wrap your UITextView in a UIView.将 UITextView 包装在 UIView 中。 Set top, leading, bottom and trailing constaints of UITextView to UIView.将 UITextView 的顶部、前导、底部和尾部约束设置为 UIView。 Perform all the transformations on UIView.在 UIView 上执行所有转换。 You should be good to go.你应该可以走了。

I have the same issue and I saw this problem, after that I fixed it like this;我有同样的问题,我看到了这个问题,之后我就这样解决了;

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()
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM