簡體   English   中英

出現鍵盤時的滾動視圖:庫還是DIY?

[英]Scrolling view when keyboard appears: Library or DIY?

當用戶點擊相應的對象看起來無縫時,我想盡一切辦法使整個視圖移到適當的UITextField 我知道我並不是唯一一個絕對不喜歡這樣做的人。

用最少的工作量使工作盡可能精美的最佳方法是什么?

我已經嘗試了TPKeyboardAvoiding ,它完全爛透了

現在,我已經編寫了這段代碼,但是它以其自己的特殊方式也很爛:

- (void)viewDidLoad
{
    self.view.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin);
    self.scrollView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin);

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
}


- (void)keyboardWasShown:(NSNotification *)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    self.scrollView.contentInset = contentInsets;
    self.scrollView.scrollIndicatorInsets = contentInsets;

    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your application might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    if (!CGRectContainsPoint(aRect, self.activeField.frame.origin) ) {
        CGPoint scrollPoint = CGPointMake(0.0, self.activeField.frame.origin.y-kbSize.height);
        [self.scrollView setContentOffset:scrollPoint animated:YES];
    }
}

- (void)keyboardWillBeHidden:(NSNotification *)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    self.scrollView.contentInset = contentInsets;
    self.scrollView.scrollIndicatorInsets = contentInsets;
}

對我來說,它可以工作TPKeyboardAvoiding ,我在所有項目中都使用它。 您是否嘗試過:

  1. 將UIScrollView添加到視圖控制器的xib中
  2. 將滾動視圖的類設置為TPKeyboardAvoidingScrollView(仍通過身份檢查器在xib中)
  3. 將所有控件都放在該滾動視圖中?

我也找到了這個解決方案: 鍵盤管理器

  1. 下載演示項目
  2. 只需將KeyboardManager和SegmenedNextPrevious類拖放到您的項目中
  3. 在您的appDelegate中,只編寫一行代碼:

    [KeyBoardManager installKeyboardManager];

祝好運!

您是否知道,如果您的視圖控制器是從UITableViewController派生的,那么當文本字段或文本視圖獲得焦點時,當鍵盤顯示時,表視圖的滾動是自動的? 您不必做任何事情。 話雖這么說,但是對於您的應用來說,重構UI可能不太好,因此它使用帶有靜態單元格的表視圖來代替您現在正在做的任何事情。

如果這對您contenSize ,則可以在顯示鍵盤時將滾動視圖的contenSize更改為可見區域的大小,然后在滾動視圖上調用scrollRectToVisible:animated : ,將其傳遞給鍵盤內部文本字段的rectWasShown:選擇器。

暫無
暫無

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

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