Reputation: 1783
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.
Upvotes: 6
Views: 4910
Reputation: 19737
If you are using UITextView
, you can simply make it fit to its content by setting:
textView.isScrollEnabled = false
This will make it grow with the input.
Upvotes: 3
Reputation: 4928
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.
Upvotes: 3
Reputation: 9
All you need to do for a UITextView to grow automatically is to set numberOfLines to 0. Then it will grow infinitely. I hope that works for you!
Upvotes: -4