2013-11-01 128 views
11

我有我的故事板,顯示用戶登錄形式的一個觀點,所以它看起來是這樣的:主視圖 - >滾動查看 - >內容查看 - >兩個文本字段,並在登錄按鈕頂部和一個註冊按鈕在視圖的底部。我使用自動佈局,底部按鈕有底部空間限制。當我點擊文本字段並出現鍵盤時,我想滾動視圖以將大小更改爲可見矩形,但內容大小應保持向下滾動到註冊按鈕,但當滾動視圖大小更改時,按鈕向上移動。我怎麼能做我想要的?iOS的自動版式與滾動視圖和鍵盤

我使用此代碼鍵盤出現時:

- (void)keyboardWillShow:(NSNotification *)aNotification 
{ 
    NSDictionary *info = [aNotification userInfo]; 
    NSValue *kbFrame = [info objectForKey:UIKeyboardFrameEndUserInfoKey]; 
    NSTimeInterval animationDuration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]; 
    CGRect keyboardFrame = [kbFrame CGRectValue]; 

    CGSize s = self.scrollView.contentSize; 
    CGFloat height = keyboardFrame.size.height; 
    self.scrollViewBottomLayoutConstraint.constant = height; 

    [UIView animateWithDuration:animationDuration animations:^{ 
     [self.view layoutIfNeeded]; 
     [self.scrollView setContentSize:s]; 
    }]; 
} 

回答

29

嘗試獨自一人出走內容的大小,而是調整滾動視圖的contentInset財產。那麼你不必混淆約束。

- (void)keyboardUp:(NSNotification *)notification 
{ 
    NSDictionary *info = [notification userInfo]; 
    CGRect keyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; 
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil]; 

    UIEdgeInsets contentInset = self.scrollView.contentInset; 
    contentInset.bottom = keyboardRect.size.height; 
    self.scrollView.contentInset = contentInset; 
} 
+0

謝謝。有用。 –

+0

很好的回答;對我很好!謝謝! –

+1

不錯,簡單,但一個問題是滾動視圖欄不會調整到scroll/table/collection視圖的可見部分。 –

1

我發現,最好的方法是重寫NSLayoutConstraint像這樣:

@implementation NHKeyboardLayoutConstraint 

- (void) dealloc { 
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
} 

- (void) awakeFromNib { 
    [super awakeFromNib]; 
    [[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(keyboardWillChangeFrame:) 
               name:UIKeyboardWillChangeFrameNotification 
               object:nil]; 
} 

- (void)keyboardWillChangeFrame:(NSNotification *)notification { 

    CGRect endKBRect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; 

    CGFloat animationDuration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue]; 
    CGRect frame = [UIApplication sharedApplication].keyWindow.bounds; 

    self.constant = frame.size.height - endKBRect.origin.y; 


    [UIView animateWithDuration:animationDuration animations:^{ 
     [[UIApplication sharedApplication].keyWindow layoutIfNeeded]; 
    }]; 
} 


@end 

然後在廈門國際銀行更改類類型的違規約束這一類。