简体   繁体   English

如何在Swift中修复UITextView文本内容位置

[英]How to fix UITextView text content position in Swift

I have UIView class and in this class have UITextView for use as inputText 我有UIView类,并且在此类中有UITextView用作inputText

In textViewDidChange from row 2 through 5 with any inter, or adding text, I add the UITextView bounds.size.height as much as need. textViewDidChange从行2至5与任何内部或添加文字,我想补充UITextView bounds.size.height不亚于需要。

The problem is, in rows 3 and 5, first line text does not appear. 问题是,在第3行和第5行中,第一行文本没有出现。 To be roughly a row above its own space. 大约在其自身空间上方一行。 And is created from the bottom of the empty space, without scrolling. 并且是从空白区域的底部创建的,无需滚动。

But the text in the 4th row have exact position 但是第4行中的文字有确切的位置

class QuestionCell: UIView, UITextViewDelegate{

    var paragraph = UITextView()

    func setParagraph(){
        let frame = CGRect(x: 50,
                           y: 0,
                           width: forground.width-55,
                           height: forground.height)
        paragraph.frame = frame
        paragraph.isEditable = true
        paragraph.delegate = self
        // forground is some UIView in this View
        forground.addSubview(paragraph)
    }
    func textViewDidChange(_ textView: UITextView) {
       paragraph.bounds.size.height = paragraph.paragraphHeight
    }
}

extension UITextView{
    var paragraphHeight: CGFloat{
        let fixedWidth = self.width
        let newSize = self.sizeThatFits(CGSize.init(width: fixedWidth,
                                                         height: CGFloat(MAXFLOAT)))
        var newFrame = self.frame
        newFrame.size = CGSize.init(width: CGFloat(fmaxf(Float(newSize.width),
                                                         Float(fixedWidth))),
                                    height: newSize.height)
        return newSize.height
    }
}

During Creating you need to specify : 在创建期间,您需要指定:

  paragraph.isScrollEnabled = false

After creating, you may set it back. 创建后,可以将其重新设置。

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

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