簡體   English   中英

帶有滾動視圖和鍵盤的iOS AutoLayout

[英]iOS AutoLayout with scrollview and keyboard

我在故事板上有一個視圖來顯示用戶登錄表單,所以它看起來像這樣:主視圖 - >滾動視圖 - >內容視圖 - >頂部的兩個文本字段和登錄按鈕以及底部的一個注冊按鈕風景。 我使用自動布局,底部按鈕有底部空間約束。 當我點擊文本字段並出現鍵盤時,我想滾動視圖以將大小更改為可見的rect,但內容大小應保持向下滾動到注冊按鈕,但當滾動視圖的大小更改時按鈕會向上移動。 我怎么能做我想要的?

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

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

嘗試單獨保留內容大小,而是調整滾動視圖的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;
}

我發現的最好方法是覆蓋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

然后在你的xib中將違規約束的類類型更改為此類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM