ios - UITextView resizes the height dynamically with restricting maximum height -


i want make textview whatsapp resizing textview's height when typing long string. once reaches maximum height, textview's remained maximum height , textview becomes scrollable. same whatsapp's textview when replying message.

i found way resize dynamically, when set textview.isscrollenabled = true once reaches maximum height, textview shrink scrollable.

how can make textview whatsapp's textview?

override func viewdidload() {     super.viewdidload()     notificationcenter.default.addobserver(self, selector: #selector(updateheight), name: nsnotification.name.uitextviewtextdidchange, object: nil)     textview.isscrollenabled = false     // ... }  func updateheight() {     var contentsize = textview.sizethatfits(textview.bounds.size)     contentsize.width = uiscreen.main.bounds.width     if contentsize.height > uiscreen.main.bounds.height / 5{         textview.isscrollenabled = true         contentsize.height = uiscreen.main.bounds.height / 5     } else {         textview.isscrollenabled = false     }     textview.frame.size = contentsize } 

enter image description here

extension viewcontroller : uitextviewdelegate{

func textview(_ textview: uitextview, shouldchangetextin range: nsrange, replacementtext text: string) -> bool{      let cursorposition = self.textview.caretrect(for: self.tvchat.selectedtextrange!.start).origin     let currentline = int(cursorposition.y / self.tvchat.font!.lineheight)       uiview.animate(withduration: 0.3) {         if currentline == 0 {             self.constraintheighttextview.constant = 56         }else {             self.constraintheighttextview.constant = self.textview.contentsize.height + 8 // padding         }     }     self.textview.layoutifneeded()     self.view.updateconstraints() } 

}

self.constraintheighttextview outlet textview's height constraint.

as text changes in textview can calculate current line of text working on , update constraint default (56 in case) if currentline 0 else set textview.contentsize.height.

hope helps


Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -