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 }
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
Post a Comment