为什么我的UIScrollView在键盘弹出时滚动错误



因此,对于那些希望在键盘出现时将视图向上推的人,我经常建议使用UIScrollView。我复制并粘贴了这个页面上的信息——http://developer.apple.com/library/ios/#documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html#//apple_ref/doc/uid/TP40009542-CH5-SW7——来做到这一点。

但实际情况是,当我点击文本字段时,键盘弹出,但视图实际上向下滚动,顶部显示黑色。之后,我可以手动向上滚动视图并显示隐藏的文本字段…很明显,这不是我要做的!

任何想法?我在viewDidLoad()方法中有以下内容:- (void)viewDidLoad

{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
}

我试过这个版本的keyboardwasshowed:

- (void) keyboardWasShown:(NSNotification *)aNotification
{
    NSDictionary * info = [aNotification userInfo];
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0, 0,keyboardSize.height, 0);
    [[self introScroll] setContentInset:contentInsets];
    [[self introScroll] setScrollIndicatorInsets:contentInsets];
    CGRect ltdRect=[[self view] frame];
    ltdRect.size.height=keyboardSize.height;
    if (!CGRectContainsPoint(ltdRect,[self activeField].frame.origin))
    {
        CGPoint scrollPoint = CGPointMake(0,[self activeField].frame.origin.y-keyboardSize.height);
        [[self introScroll] setContentOffset:scrollPoint animated:YES];
    }
    NSLog(@"Keyboard out!");
}

以及这个版本的keyboardwasshowed:

- (void)keyboardWasShown:(NSNotification*)aNotification {
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    CGRect bkgndRect = [[[self activeField] superview ]frame];
    bkgndRect.size.height += kbSize.height;
    [[[self activeField] superview] setFrame:bkgndRect];
    [[self introScroll] setContentOffset:CGPointMake(0.0, [self activeField].frame.origin.y-kbSize.height) animated:YES];
}

两者的结果完全相同。

怎么回事??我用的是Xcode 4.6

我有一个类似的问题,我的文本字段没有滚动到视图
苹果的代码并不完美,我不得不修改它。尝试通过添加活动字段的高度来解决这个问题:

frame.origin.y + frame.size.height - keyboardSize.height

如果不工作,添加44到滚动点。Y(导航条大小)

更新为ios7:

我改进了ios7中文本字段不必要的和错误的滚动,这已经在视图中

if (scrollPtY < 0) {
        return;
}

最新更新