I am trying un the past two days to implement a UITextView that grows as the user types. Like whats-app does.
I've found examples here with textViewDidChange but that didn't really work as it needs to not only grow but also move upwards. And as the textview sits inside a view that also holds the send button, they both have to grow upwards.
Also found some other frameworks.
https://github.com/slackhq/SlackTextViewController - looks really cool and may do everything I need but I found no examples of it running swift. The sample project provided I could not run.
https://github.com/MatejBalantic/MBAutoGrowingTextView - could not really get it to work upwards.
I am looking for some help on how to implement that using SWIFT or maybe a sample project of the SLACK one running on swift that is not the sample project on github. Or maybe a bit of code showing how to link the UITextView to the Slack class and make it work inside a viewController class.
Here's what I'm currently using for my inputAccessoryView.
I have a toolbar that holds the UITextView and send button and listens to textViewDidChange events like so:
func textViewDidChange(_ textView: UITextView) {
let oldHeight = textView.height
let maxHeight: CGFloat = 100.0 //beyond this value the textView will scroll
var newHeight = min(textView.sizeThatFits(CGSize(width: textView.frame.width, height: CGFloat.greatestFiniteMagnitude)).height, maxHeight)
newHeight = ceil(newHeight)
if newHeight != oldHeight {
textView.frame.size.height = max(newHeight, barHeight)
updateHeight(height: newHeight)
}
}
The goal here is to set the new textView height. Then I update the toolbar height as well
public func updateToolBarHeight(height: CGFloat) {
for constraint in constraints {
if constraint.firstAttribute == NSLayoutAttribute.height && constraint.firstItem as! NSObject == self {
constraint.constant = max(barHeight, height)
}
}
setNeedsUpdateConstraints()
sendButton.origin.y = max(0, height - barHeight)
}
barHeight is my default toolbar height (set to 50.0). and I also update my sendButton position to stay at the bottom of the toolbar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With