How to entirely disable UITextView's scroll?

梦想与她 提交于 2019-12-21 02:55:29

问题


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

myTextView.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?


回答1:


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];
}


来源:https://stackoverflow.com/questions/4652138/how-to-entirely-disable-uitextviews-scroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!