2011-03-19 57 views
0

這是我的代碼如下:無法滾動?我的代碼有什麼問題?

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

回答

0

有兩個問題。首先,您應該使用UIKeyboardFrameEndUserInfoKey而不是UIKeyboardFrameBeginUserInfoKey

其次,在將其轉換爲視圖的本地座標空間之後,您確實應該使用鍵盤的原點。如果設備處於橫向模式或視圖的座標不同於窗口的座標,只使用返回的幀而不使用 - [UIView convertRect:fromView:]將不起作用。您應該使用變換座標的原點而不是高度,因爲高度可能指的是屏幕外的部分鍵盤。例如,使用藍牙鍵盤時會發生這種情況。