How to adjust the height of a textview to his content in SWIFT?

前端 未结 7 734
无人及你
无人及你 2020-12-07 23:05

In my view controller, I have an UITextView. This textview is filled with a string. The string can be short or long. Depending on the length of the string, the height of the

相关标签:
7条回答
  • 2020-12-07 23:57

    I found a solution.

    I was focus on the height of my UITextView, then I read a post talking about the aspect ratio. I wanted to try and that worked!

    So in the storyboard, I added an aspect ratio for the textview, and I checked "Remove at build time" option.

    In viewDidLayoutSubviews(), I wrote :

    override func viewDidLayoutSubviews() {
    
        super.viewDidLayoutSubviews()
    
        let contentSize = self.myTextViewTitle.sizeThatFits(self.myTextViewTitle.bounds.size)
        var frame = self.myTextViewTitle.frame
        frame.size.height = contentSize.height
        self.myTextViewTitle.frame = frame
    
        aspectRatioTextViewConstraint = NSLayoutConstraint(item: self.myTextViewTitle, attribute: .Height, relatedBy: .Equal, toItem: self.myTextViewTitle, attribute: .Width, multiplier: myTextViewTitle.bounds.height/myTextViewTitle.bounds.width, constant: 1)
        self.myTextViewTitle.addConstraint(aspectRatioTextViewConstraint!)
    
    }
    

    It works perfectly.

    0 讨论(0)
提交回复
热议问题