3

I'm trying to create a text view which height follows number of line in it. I've worked on constraint but here I've a curious issue :

  • At the beginning all is centered as I want

enter image description here

  • When there is a break, text is not vertically centered anymore and goes in top left corner

enter image description here

  • When you delete characters and then come back to previous line, the text is yet vertically centered

enter image description here

Here is the code

func textViewDidChange(textView: UITextView) { //Handle the text changes here
    if(textView.text != ""){
        self.animateSendButton(true)
    }else{
        self.animateSendButton(false)
    }//the textView parameter is the textView where text was changed

    heightTextfieldConstraint.constant = self.textField.contentSize.height + 2
    textField.contentInset.top = 1
}

I don't understand why there are these 3 different cases, do you have any idea to solve it ?

Kubba
  • 3,390
  • 19
  • 34
Bram'in
  • 618
  • 1
  • 7
  • 18

3 Answers3

5

You can try and add an inset to the top, bot, left and right, that should keep the text centered even after a second line appears.

textView.textContainerInset = UIEdgeInsetsMake(5, 5, 5, 5)
Diogo Antunes
  • 2,241
  • 1
  • 22
  • 37
2

You might be better off keeping the text view itself vertically centered while ensuring that the text view is always sized to fit the content. You can do this with Auto Layout.

Set the text view to be vertically centered in its container and also add a height constraint to the text view with a low constant value (about the height of 1 line of text). Then set the text view's Content Compression Resistant Priority to a value that is higher than the text view's height constraint (see screenshots).

enter image description here enter image description here

I've done it in "Main.storyboard" of this demo project of mine if you want to see a working example: https://github.com/patricklynch/Walkthrough

Patrick Lynch
  • 2,742
  • 1
  • 16
  • 18
  • I've tried and it works however I would like to increase the container's height when text view grow up. Here after two line the text view becomes scrollable. Do you have a solution for this ? – Bram'in Jun 12 '16 at 21:43
0

Perhaps you could call view.layoutIfNeeded() after text has been entered.

Pranav Wadhwa
  • 7,666
  • 6
  • 39
  • 61