iOS-鍵盤常見處理,自定義鍵盤上的工具條、定義鍵自盤方法等

場景一說明

在iOS開發中,咱們常常處理這樣的狀況:工具

當鍵盤出現或者消失的時候,咱們須要作一些相應的操做。好比鍵盤上面的工具條的位置變化等。動畫

這裏咱們就假設有一個工具條在鍵盤的上面,咱們要求當鍵盤出現的時候,工具條的位置向上移動始終在鍵盤的上面,當鍵盤消失的時候,工具條向下移動到屏幕的下面。code

這時候,咱們應該怎麼處理呢?orm

思路

  • 爲了讓工具條上下移動,咱們就要求出鍵盤上下移動的高度值,從而知道工具條該上下移動的高度值
  • 想獲取鍵盤的移動值,就要對鍵盤的顯示和隱藏進行監聽,咱們這裏可使用通知

是否是以爲思路很清晰了,那麼開始吧。server

處理步驟

  • 一、給鍵盤設一個通知
/**
     *  給鍵盤的frame改變添加監聽
     *  @param keyBoardWillChangeFrame: 監聽方法
     */
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
  • 二、在鍵盤的通知監聽方法裏面作須要的操做
- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
    // 鍵盤顯示\隱藏完畢的frame
    CGRect frame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    // 修改底部約束
    self.bottomSapce.constant = XMGScreenH - frame.origin.y;
    // 動畫時間
    CGFloat duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    // 動畫
    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
}

上一段代碼解釋:開發

notification.userInfo:rem

  • notification是指傳遞過來的通知
  • userInfo是一個字典,存儲任何和通知相關聯的可能用到的信息。當一個通知的值發生改變的時候,就會將值存儲到userInfo的字典中。例如這裏的userInfo包含通知執行的時間,和通知結束時候鍵盤的frame等信息。
  • 也能夠改變工具條的transform實現:
self.toolbar.transform = CGAffineTransformMakeTranslation(0, -keyboardF.size.height);

自定義鍵盤,只須要設置下面的屬性便可

@property (readwrite, retain) UIView *inputView;

最後,必定要記得在dealoc方法裏釋放監聽input

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

場景二說明

有時候在同一個界面裏面,可能有多個TextField輸入框,而點擊不一樣額輸入框,咱們可能但願彈出的鍵盤擁有不一樣的工具條,這時候咱們怎麼辦呢?animation

思路

  • 首先咱們要有那麼幾種工具條,可使用xib方式(簡單,不講解了了,不知道能夠發郵件給我)
  • 而後設置不一樣輸入框的配件視圖(textField.inputAccessoryView = xxxTool)
  • 設置輸入框成爲第一響應者,這樣彈出的時候就能有不一樣的toolBar了。

代碼實現

//這裏不貼圖了,比較簡單
UIView *tool1 = [[[NSBundle mainBundle] loadNibNamed:@"ToolBar1" owner:nil options:nil] lastObject];
UIView *tool2 = [[[NSBundle mainBundle] loadNibNamed:@"ToolBar2" owner:nil options:nil] lastObject];
self.textField1.inputAccessoryView = tool1;
self.textField2.inputAccessoryView = tool2;

經常使用知識點:

成爲第一響應者(能夠調出鍵盤)it

- (BOOL)becomeFirstResponder;

取消第一響應者

- (BOOL)resignFirstResponder;

所有取消第一響應者

- (BOOL)endEditing:(BOOL)force;    //使用這個使得view或者其全部的子視圖都取消第一響應者 (optionally force)
相關文章
相關標籤/搜索