我想在键入时调整textview的大小,但是使用此代码,我没有更改宽度。每次我获得的textView大小为200时,哪里出错了?请帮帮我。
预先感谢
let textViewX = UITextView(frame: CGRect(x: self.view.frame.width / 2 - 100, y: self.view.frame.height / 2 - 25, width: 200, height: 50))
textViewX.isScrollEnabled = false
textViewX.clipsToBounds = false
textViewX.delegate = self
textViewX.font = UIFont.systemFont(ofSize: 25)
self.view.addSubview(textViewX)
func textViewDidChange(_ textView: UITextView) {
let fixedWidth = textView.frame.size.width
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
textView.frame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
}
答案 0 :(得分:1)
您的问题是,您使用newSize
方法告诉fixedWidth
,它不能比sizeThatFits(:)
宽。如果更改代码以允许更大的宽度,则textView会水平增长:
let fixedHeight = textView.frame.size.height
let newSize = textView.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: fixedHeight))
textView.frame.size = newSize
这允许textView的框架仅水平增长。要允许两者,您可以尝试这样的事情:
let maxWidth = UIScreen.main.bounds.width - 20
let maxHeight = UIScreen.main.bounds.height - 20
let newSize = textView.sizeThatFits(CGSize(width: maxWidth, height: maxHeight))
textView.frame.size = newSize
textView.center = view.center
这可以使框架垂直和水平增长,将textView保持在其父视图的中心,并限制textView的大小为屏幕的大小(四周有20 pt的边界)。