我有一个UIScrollView
,里面有几个动态视图,每个视图都有一个文本字段。当我开始在其中一个框中键入内容时,我希望滚动视图滚动,以便该字段位于屏幕顶部(在键盘上方可见)。它很棒;这是代码:
(void)didStartTyping:(id)sender {
[scrollView setContentOffset:CGPointMake(0, subView.frame.origin.y) animated:YES];
scrollView.scrollEnabled = NO;
}
(void)didFinishTyping:(id)sender {
scrollView.scrollEnabled = YES;
}
但是,每当滚动视图向上滚动到最顶部并且我开始在最低的可见文本字段中键入时,它就不会向下滚动得足够远(短约40 px)。令人费解的是,如果我从滚动视图的顶部向下滚动一个像素,它就可以工作,但是当我向上滚动到顶部时,它的表现非常不同。
答案 0 :(得分:2)
我设法做到这一点的最好方法是抓取键盘框架,然后在文本视图获得textViewDidBeginEditing:called时更新我的scrollview插件。这里我使用tableview,但相同的逻辑应该适用于scrollview,主要区别在于你如何滚动。我使用scrollToRowAtIndexPath,你会想要使用scrollRectToVisible
//setup keyboard callbacks
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillHideNotification
object:nil];
}
- (void)keyboardWillShow:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
kbFrame = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
}
//this is called from your UITextViewDelegate when textViewDidBeginEditing: is called
- (void)updateActiveTextScroll:(UITextView*)textView
{
activeTextView = textView;
UIEdgeInsets inset;
UIInterfaceOrientation orient = [[UIApplication sharedApplication] statusBarOrientation];
if( UIInterfaceOrientationIsLandscape(orient) )
{
inset = UIEdgeInsetsMake(0.0, 0.0, kbFrame.size.width, 0.0);
}
else
{
inset = UIEdgeInsetsMake(0.0, 0.0, kbFrame.size.height, 0.0);
}
myTableView.contentInset = inset;
myTableView.scrollIndicatorInsets = inset;
[myTableView scrollToRowAtIndexPath:activeNSIndexPath
atScrollPosition:UITableViewScrollPositionBottom
animated:YES];
}
//dont forget to reset when the keyboard goes away
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
UIEdgeInsets inset = UIEdgeInsetsZero;
myTableView.contentInset = inset;
myTableView.scrollIndicatorInsets = inset;
}