iOS 切換鍵盤

weixin_30924079發表於2020-04-04

1.點選toolbar的加號按鈕切換鍵盤

       切換前                 切換後

      

 

2 要實現上述效果

2.1 需要監聽鍵盤的彈出\隱藏

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; 

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

 1 /**
 2  *  鍵盤即將隱藏
 3  */
 4 - (void)keyboardWillHide:(NSNotification *)note
 5 {
 6     // 1.鍵盤彈出需要的時間
 7     CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
 8     // 2.動畫
 9     [UIView animateWithDuration:duration animations:^{
10         self.toolbar.transform = CGAffineTransformIdentity;
11     }];
12 }
 1 /**
 2  *  鍵盤即將彈出
 3  */
 4 - (void)keyboardWillShow:(NSNotification *)note
 5 {
 6     // 1.鍵盤彈出需要的時間
 7     CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
 8     // 2.動畫
 9     [UIView animateWithDuration:duration animations:^{
10         // 取出鍵盤高度
11         CGRect keyboardF = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
12         CGFloat keyboardH = keyboardF.size.height;
13         self.toolbar.transform = CGAffineTransformMakeTranslation(0, - keyboardH);
14     }];
15 }

2.2 toolbar的懶載入方法

 1 - (UIToolbar *)toolbar{
 2     if (_toolbar == nil) {
 3         _toolbar = [[UIToolbar alloc]init];
 4         _toolbar.frame = CGRectMake(0, screenHeight - kToolbarHeight , screenWidth, kToolbarHeight);
 5         [self.view addSubview:_toolbar];
 6         
 7         // 切換鍵盤的按鈕
 8         UIButton *changeKeybord = [UIButton buttonWithType:UIButtonTypeContactAdd];
 9         [_toolbar addSubview:changeKeybord];
10 
11         [changeKeybord addTarget:self action:@selector(changeKeybord) forControlEvents:UIControlEventTouchDown];
12     }
13     return _toolbar;
14 }

2.3 實現changeKeybord方法

 1 - (void)changeKeybord
 2 {
 3     if (self.mytext.inputView) { //inputView存在則說明是自定義鍵盤
 4         self.mytext.inputView = nil; //把自定義鍵盤清空,則就變回系統鍵盤
 5     }else{ //反之,inputView不存在,則說明當前顯示的是系統鍵盤
 6         UIView *newKeybord = [[UIView alloc]init];  // 例項化一個新鍵盤
 7         newKeybord.bounds = CGRectMake(0, 0, 320, 216);
 8         newKeybord.backgroundColor = [UIColor yellowColor];
 9         self.mytext.inputView = newKeybord; //將新鍵盤賦值給inputView
10     }
11 
12     // 下面這句不能省,因為切換鍵盤後,只有先隱藏再彈出,才會調出新鍵盤
13     [self.mytext resignFirstResponder];
14     // 為了讓鍵盤切換互動效果更順暢,增加延遲,如果不增加延遲,會出現:舊鍵盤還沒完全隱藏,新鍵盤就已經彈出了
15     dispatch_after((uint64_t)3.0, dispatch_get_main_queue(), ^{
16         [self.mytext becomeFirstResponder];
17     });
18     
19 }

2.4 自定義一個新鍵盤

未完待續

轉載於:https://www.cnblogs.com/oumygade/p/4223025.html

相關文章