UITextView
是 的子类UIScrollView
,因此答案涉及contentOffset
属性,即正在更改的内容,而不是插入或内容大小。如果视图首次出现时滚动位置正确,则可以存储内容偏移量以供以后调用。
YourViewController.h 被剪断
@interface YourViewController : UIViewController <UITextViewDelegate, UIScrollViewDelegate>
@property(nonatomic, weak) IBOutlet UITextView *textView;
@end
YourViewController.m 片段
@implementation YourViewController {
@private
BOOL _freezeScrolling;
CGFloat _lastContentOffsetY;
}
// UITextViewDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView {
// tell the view to hold the scrolling
_freezeScrolling = YES;
_lastContentOffsetY = self.textView.contentOffset.y;
}
// UITextViewDelegate
- (void)textViewDidEndEditing:(UITextView *)textView {
_freezeScrolling = NO;
}
// UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (_freezeScrolling) {
// prevent the scroll view from actually scrolling when we don't want it to
[self repositionScrollView:scrollView newOffset:CGPointMake(scrollView.contentOffset.x, _lastContentOffsetY)];
}
}
// UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
// scroll prevention should only be a given scroll event and turned back off afterward
_freezeScrolling = NO;
}
// UIScrollViewDelegate
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
// when the layout is redrawn, scrolling animates. this ensures that we are freeing the view to scroll
_freezeScrolling = NO;
}
/**
This method allows for changing of the content offset for a UIScrollView without triggering the scrollViewDidScroll: delegate method.
*/
- (void)repositionScrollView:(UIScrollView *)scrollView newOffset:(CGPoint)offset {
CGRect scrollBounds = scrollView.bounds;
scrollBounds.origin = offset;
scrollView.bounds = scrollBounds;
}
在上面的代码示例中还需要注意的是最后一种方法。调用任何类型的setContentOffset:
实际上都会触发滚动,从而导致调用scrollViewDidScroll:
. 所以调用setContentOffset:
会导致无限循环。设置滚动边界是解决此问题的方法。
简而言之,UITextView
当我们检测到用户选择了要编辑的文本时,我们告诉视图控制器阻止滚动。我们还存储当前内容偏移量(因为我们知道该位置是我们想要的)。如果UITextView
尝试滚动,那么我们将内容偏移保持在适当的位置,直到滚动停止(这会触发scrollViewDidEndDecelerating:
或scrollViewDidEndScrollingAnimation:
)。当用户完成编辑时,我们也会解冻滚动。
请记住,这是一个基本示例,因此您需要根据您想要的确切行为调整代码。