I am making a an app that has a UITextView
and a button.
When I click the button some text will add in the UITextView
.
But when c
As a generic approach for scrolling to bottom, it can be done on a UIScrollView.
extension UIScrollView {
func scrollToBottom() {
let contentHeight = contentSize.height - frame.size.height
let contentoffsetY = max(contentHeight, 0)
setContentOffset(CGPoint(x: 0, y: contentoffsetY), animated: true)
}
}
This will work on all descendants of UIScrollView like UITextView, UITableView etc..
You can use the following code if you are talking about UITextView:
-(void)scrollTextViewToBottom:(UITextView *)textView {
if(textView.text.length > 0 ) {
NSRange bottom = NSMakeRange(textView.text.length -1, 1);
[textView scrollRangeToVisible:bottom];
}
}
SWIFT 4:
func scrollTextViewToBottom(textView: UITextView) {
if textView.text.count > 0 {
let location = textView.text.count - 1
let bottom = NSMakeRange(location, 1)
textView.scrollRangeToVisible(bottom)
}
}
The Swift version of @Hong Duan answer
func scrollTextViewToBottom(textView: UITextView) {
if textView.text.count > 0 {
let location = textView.text.count - 1
let bottom = NSMakeRange(location, 1)
textView.scrollRangeToVisible(bottom)
// an iOS bug, see https://stackoverflow.com/a/20989956/971070
textView.isScrollEnabled = false
textView.isScrollEnabled = true
}
}
With Swift 3
let bottom = self.textView.contentSize.height - self.textView.bounds.size.height
self.textView.setContentOffset(CGPoint(x: 0, y: bottom), animated: true)
textView.scrollRangeToVisible(NSRange(..<textView.text.endIndex, in: textView.text))
This solution does a couple of notable things slightly different:
String.Index
interface (likely more performant than e.g. .count
)PartialRangeUpTo
which avoids an explicit range start position, reducing the code to a clean one-linerYou have to implement a delegate method. The code below checks whether a newline has been entered and, if so, scrolls to the bottom of the textView:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if ([text isEqualToString:@"\n"]) {
textView.contentOffset = CGPointMake(0.0, textView.contentSize.height);
}
return YES;
}