簡體   English   中英

移動視圖,以便鍵盤不隱藏文本字段

[英]Move view when so that keyboard does not hide text field

在我的應用程序中,當我單擊文本字段時,鍵盤會隱藏它。 請幫助我 - 當我點擊文本字段時,如何移動我的視圖。 我在textFieldDidBeginEditing:使用此代碼textFieldDidBeginEditing:

self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 216, 0);
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 216, 0);

但它不起作用。

您不應該信任textFieldDidBeginEditing:調整鍵盤,因為即使用戶使用不顯示屏幕鍵盤的物理鍵盤進行鍵入,也會調用此方法。

而是收聽UIKeyboardWillShowNotification ,它僅在實際顯示鍵盤時觸發。 您需要執行三個步驟:

  1. 從通知userInfo字典中確定鍵盤的實際大小。 尺寸將不同於橫向/縱向和不同的設備。
  2. 使用確定的大小更新contentInset 你可以動畫制作,通知甚至可以告訴你鍵盤動畫的持續時間。
  3. 將文本域滾動到視圖中,很容易忘記這一點!

您可以從此處找到更多信息和示例代碼

您可以執行以下操作,但首先要確保已將UITextField委托設置為您自己和

#define kOFFSET_FOR_KEYBOARD 350;

在頂部。 這是您希望視圖移動的距離

//method to move the view up/down whenever the keyboard is shown/dismissed

-(void)setViewMovedUp:(BOOL)movedUp
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3]; // if you want to slide up the view
    [UIView setAnimationBeginsFromCurrentState:YES];

    CGRect rect = self.view.frame;
    if (movedUp)
    {
        // 1. move the view's origin up so that the text field that will be hidden come above the keyboard 
        // 2. increase the size of the view so that the area behind the keyboard is covered up.

        if (rect.origin.y == 0 ) {
            rect.origin.y -= kOFFSET_FOR_KEYBOARD;
            //rect.size.height += kOFFSET_FOR_KEYBOARD;
        }

    }
    else
    {
        if (stayup == NO) {
            rect.origin.y += kOFFSET_FOR_KEYBOARD;
            //rect.size.height -= kOFFSET_FOR_KEYBOARD;
        }
    }
    self.view.frame = rect; 
    [UIView commitAnimations];
}


- (void)keyboardWillHide:(NSNotification *)notif {
    [self setViewMovedUp:NO];
}


- (void)keyboardWillShow:(NSNotification *)notif{
    [self setViewMovedUp:YES];
}


- (void)textFieldDidBeginEditing:(UITextField *)textField {
    stayup = YES;
    [self setViewMovedUp:YES];
}


- (void)textFieldDidEndEditing:(UITextField *)textField {
    stayup = NO;
    [self setViewMovedUp:NO];
}

- (void)viewWillAppear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) 
                                                 name:UIKeyboardWillShowNotification object:self.view.window];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) 
                                                 name:UIKeyboardWillHideNotification object:self.view.window];
}

- (void)viewWillDisappear:(BOOL)animated
{
    // unregister for keyboard notifications while not visible.
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

暫無
暫無

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

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