无法滚动?我的代码出了什么问题?

时间:2011-03-19 04:01:01

标签: iphone objective-c cocoa-touch ios4

这是我的代码如下:

-(void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];

    NSLog(@"------>> Reigster for keyboard events");
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardDidShow:) 
                                                 name:UIKeyboardDidShowNotification 
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardDidHide:) 
                                                 name:UIKeyboardDidHideNotification 
                                                object:nil];

    keyboardVisible = NO;
}

-(void) viewWillDisappear:(BOOL)animated {
    NSLog(@"--->>Unregister keyboard event");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


-(void)keyboardDidShow:(NSNotification *) notif{
    NSLog(@"Received did show notifiation");

    if (keyboardVisible) {
        NSLog(@"Keyboard is already visible... ignoring notification");
        return;
    }

    NSLog(@"Resizing smaller for keboard");

    NSDictionary *info = [notif userInfo];
    NSValue *aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGSize keyboardSize = [aValue CGRectValue].size;

    CGRect viewFrame = self.view.frame;
    viewFrame.size.height -= keyboardSize.height;

    scrollView.frame = viewFrame;
    scrollView.contentSize = CGSizeMake(viewFrame.size.width, viewFrame.size.height);

    //scrollView.contentSize = CGSizeMake(296, 217);
    keyboardVisible = YES;
}


-(void) keyboardDidHide:(NSNotification *) notif {
    NSLog(@"Received did Hide notification");

    if (!keyboardVisible) {
        NSLog(@"keyboard already hidden. Ignoring notification");
        return;
    }

    NSLog(@"Resizing bigger with no keyboard");

    NSDictionary *info = [notif userInfo];
    NSValue *aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGSize keyboardSize = [aValue CGRectValue].size;

    CGRect viewFrame = self.view.frame;
    viewFrame.size.height += keyboardSize.height;

    //scrollView.contentSize = CGSizeMake(296, 417);

    scrollView.contentSize = CGSizeMake(viewFrame.size.width, viewFrame.size.height);
    keyboardVisible = NO;
}

2 个答案:

答案 0 :(得分:0)

前面已经讨论了同样的问题,我希望你去this SO question并自己找出遗漏的内容。

答案 1 :(得分:0)

有两个问题。首先,您应该使用UIKeyboardFrameEndUserInfoKey代替UIKeyboardFrameBeginUserInfoKey

其次,在将其转换为视图的局部坐标空间后,您真的应该使用键盘的原点。如果设备处于横向或您的视图坐标与窗口坐标不同,那么仅使用返回的框架而不使用 - [UIView convertRect:fromView:]将不起作用。您应该使用变换坐标的原点而不是高度,因为高度可能指的是屏幕外的键盘部分。例如,当使用蓝牙键盘时会发生这种情况。