2013-09-28 55 views
9

當鍵盤被隱藏時,滾動視圖應該回到它的原始contentInset,但它在iOS7中不起作用。設置顯示鍵盤時的scrollview的contentInset正在工作,但當鍵盤被隱藏時,scrollview的contentInset無法設置爲插入零。 代碼:iOS7 UIScrollView contentInset不起作用

- (void)viewDidAppear:(BOOL)animated 
{ 
    [super viewDidAppear:animated]; 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:Nil]; 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification object:nil]; 
} 

- (void)keyboardWasShown:(NSNotification *)notif 
{ 
    CGSize keyboardSize = [[[notif userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size; 
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0); 


    UIScrollView *scrollView = (UIScrollView *)self.view; 
    scrollView.contentInset = contentInsets; 
    scrollView.scrollIndicatorInsets = contentInsets; 

    CGRect rect = self.view.frame; 
    rect.size.height -= keyboardSize.height; 
    if (!CGRectContainsPoint(rect, self.wishContentField.frame.origin)) { 
     CGPoint point = CGPointMake(0, self.wishContentField.frame.origin.y - keyboardSize.height); 
     [scrollView setContentOffset:point animated:YES]; 
    } 

} 
- (void)keyboardWasHidden:(NSNotification *)notif 
{ 
    UIEdgeInsets zeroInsets = UIEdgeInsetsZero; 
    UIScrollView *scrollView = (UIScrollView *)self.view; 
    [scrollView setContentInset:zeroInsets]; 
    scrollView.scrollIndicatorInsets = zeroInsets; 
} 
+2

你能解釋一下它不工作(如何在鍵盤隱藏後行事)?請注意,在iOS 7上,如果您有半透明的'navigationBar',則您的視圖控制器將爲您的scrollView設置頂部插入,否則將不會設置。這可能就是這種情況,因爲你正在設置'contentInset.top = 0',所以它可能隱藏'navigationBar'或'statusBar'後面的一些內容。 –

+0

感謝您的回覆。我將頂部設置爲navigationBar.frame.size.height,現在它正在工作。 –

+1

寫一個答案,並給alex-i一些功勞;) –

回答

9

試試這個:

self.automaticallyAdjustsScrollViewInsets = NO;

這是爲我工作...

0

所以,只是因爲我還發現這個答案是有用的,這裏是什麼我做到了。我接受了@ alex-i的建議和@ yong-ho的評論。但由於某種原因,導航欄的高度還不夠。

UIEdgeInsets contentInsets = UIEdgeInsetsMake(self.navigationController.navigationBar.frame.size.height + 20.0f, 0.0, 0.0, 0.0); 
scrollView.contentInset = contentInsets; 
scrollView.scrollIndicatorInsets = contentInsets; 

就像我說的,我不得不補充20.0f或我的內容仍然被切斷。不知道爲什麼。如果我知道了,我會更新我的答案。

+0

我也遇到過這個問題,我必須添加約90到contentInsets,scrollIndicatorInsets雖然工作正常。你使用自動大小? – streem

+0

切勿使用像這樣的幻數('20.0f')。直接獲取狀態欄高度。例如,iPhone X的狀態欄高度已更改,或者在撥打電話爲「40.0f」時在早期設備上更改 – Dermot

1

它可能與contentSize不工作 VCS中設置時除外

- (void)viewDidLayoutSubviews 
{ 
    self.scrollView.contentSize = whatever 
} 

只是說你可能會反對錯了牆被砸碎你的頭

相關問題