How to entirely disable UITextView's scroll?
I'm developing a simple text editing app for iPad using UITextView. I always had some problems with UIScrollView and UITextView. I think I just expected too much things from these two.
When I set myTextView.text to another a NSString instance, scrolling automatically occurred. I could prevent this scrolling by setting
开发者_StackOverflowmyTextView.scrollEnabled = NO;
myTextView.text = newText;
myTextView.scrollEnabled = YES;
However, if I changed the selectedRange property of myTextView, scrolling occurred.
Specifically, if selectedRange's range happened on text in the current screen, scrolling didn't occur.
For example, if I select all text by tapping "Select All" property, then scrolling didn't occur. But if I select all text by setting selectedRange to NSMakeRange(0, [myTextView.text length]), then scrolling to the END (the last caret position) occured.
To solve the problems, 1) I saved the original content offset of myTextView.
CGPoint originalOffset = myTextView.contentOffset;
// change myTextView.selectedRange here
myTextView.selectedRange = originalOffset
But nothing happend.
2) I called above codes after a few seconds using NSTimer, and scroll correctly returned to the original position(offset). However, scrolling to the end first occurred and then to the top..
Is there a way to entirely prevent UITextView's scrolling for a moment?
You can disable almost all scrolling by putting the following method into your UITextView subclass:
- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated {
// do nothing
}
The reason I say "almost" all scrolling is that even with the above, it still accepts user scrolls. Though you could disable those by setting self.scrollEnabled to NO.
If you want to only disable some scrolls, then make an ivar, lets call it acceptScrolls, to determine whether you want to allow scrolling or not. Then your scrollRectToVisible method can look like this:
- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated {
if (self.acceptScrolls)
[super scrollRectToVisible: rect animated: animated];
}
精彩评论