iOS 自定義鍵盤

少年佳節倍多情,老去誰知感慨生;
不效艾符趨習俗,但祈蒲酒話升平。
鬢絲日日添白頭,榴錦年年照眼明;
千載賢愚同瞬息,幾人湮沒幾垂名。

UI想要的效果,我...只能默默的承受著

keyBoard.png

前言

端午將近,想想再過一個小時就要回家,心里難免有點激動,但是作為一個程序猿,怎么也不能閑著,于是想起了最近正在做的項目中關于自定義鍵盤,下面就與大家分享分享,因為時間關系,GLKeyBoard就寫的有點簡單,下面就來看看具體實現

思路

就以UITextField為例,在API中有這么一個屬性inputView,當我們的UITextField成為第一響應者的時候就會彈出該view,當然我們默認情況下是系統默認的鍵盤,所以,要想自定義鍵盤,就需要在此處下功夫了。

動手
  1. 想必寫這個界面,對各位是沒有什么難度的,絕對妥妥的,十來分鐘就搞定的事情,貼上部分代碼
-(void)initializeViewComponents
{
    self.backgroundColor =UICOLOR_FROM_RGB_OxFF(0xbfc5ca);
    
    NSArray *array = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0",@"千",@"萬",@"十萬",@"百萬",@"Delete",@"清除",];
    
    for (int i = 0; i < kKeyBoardNumber; i ++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = kKeyBoardTag + i;
        [button setBackgroundColor:UICOLOR_FROM_RGB_OxFF(0xfefefe)];
        if (i == kKeyBoardNumber-2) {
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [button setBackgroundColor:UICOLOR_FROM_RGB_OxFF(0xff4238)];
        }else{
            [button setTitleColor:UICOLOR_FROM_RGB_OxFF(0x303030) forState:UIControlStateNormal];
        }
        if (i > 9) {
            button.titleLabel.font = [UIFont systemFontOfSize:12];
        }else{
            button.titleLabel.font = [UIFont systemFontOfSize:15];
        }
        
        button.layer.cornerRadius = 5;
        [button.layer setMasksToBounds:YES];
        
        [button setTitle:array[i] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(keyBoardClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
        
        if (i == 0) {
            [button mas_makeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake(GTReViewXFloat(kKeyBoardWidth), GTReViewXFloat(kKeyBoardHeight)));
                make.top.equalTo(@(GTReViewXFloat(kKeyBoardTopPadding)));
                make.left.equalTo(self.mas_left).offset(GTReViewXFloat(5));
            }];
            
            _lastButton = button;
        }else if(i < 10){
            [button mas_makeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake(GTReViewXFloat(kKeyBoardWidth), GTReViewXFloat(kKeyBoardHeight)));
                make.top.equalTo(@(GTReViewXFloat(kKeyBoardTopPadding)));
                make.left.equalTo(_lastButton.mas_right).offset(GTReViewXFloat(kKeyBoardMiddlePadding));
            }];
            
            _lastButton = button;
        }else if(i == 10){
            [button mas_makeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake(GTReViewXFloat(kKeyBoardBigWidth), GTReViewXFloat(kKeyBoardHeight)));
                make.top.equalTo(_lastButton.mas_bottom).offset((GTReViewXFloat(kKeyBoardTopPadding)));
                make.left.equalTo(self.mas_left).offset(GTReViewXFloat(5));
            }];
            _lastButton = button;
        }else if (i < 14 && i > 10){
            [button mas_makeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake(GTReViewXFloat(kKeyBoardBigWidth), GTReViewXFloat(kKeyBoardHeight)));
                make.top.equalTo(_lastButton.mas_top);
                make.left.equalTo(_lastButton.mas_right).offset(GTReViewXFloat(kKeyBoardBottomMiddlePadding));
            }];
            _lastButton = button;
        }else if (i == 14){
            [button mas_makeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake(GTReViewXFloat(100), GTReViewXFloat(kKeyBoardHeight)));
                make.top.equalTo(_lastButton.mas_top);
                make.left.equalTo(_lastButton.mas_right).offset(GTReViewXFloat(kKeyBoardBottomMiddlePadding));
            }];
            _lastButton = button;
            
        }else if (i == 15){
            [button mas_makeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake(GTReViewXFloat(84), GTReViewXFloat(kKeyBoardHeight)));
                make.top.equalTo(_lastButton.mas_top);
                make.left.equalTo(_lastButton.mas_right).offset(GTReViewXFloat(kKeyBoardBottomMiddlePadding));
            }];
            _lastButton = button;
        }
    }
}

這里不建議像我這樣,把需要的鍵值寫在這里,最好是新建一個plist文件,這個布局代碼也有點亂,大家多擔待。

  1. 寫完之后,激動的我趕快想看下效果,于是飛快的寫下了下面的代碼
    GLKeyBoard *keyBoard = [[GLKeyBoard alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, GTReViewXFloat(85))];
    
    _textFiled = [[UITextField alloc] init];
    _textFiled.delegate = (id)self;
    _textFiled.textColor = [UIColor orangeColor];
    _textFiled.borderStyle = UITextBorderStyleRoundedRect;
    _textFiled.placeholder = @"隨便輸...";
    _textFiled.inputView = keyBoard;
    [self.view addSubview:_textFiled];

正當我興奮不已的時候,我艸,什么鬼,點了按鈕都沒反應,恍然大悟,原來按鈕點擊那里什么都沒處理....

  1. 進入按鈕點擊后的核心處理
    首先,我們的在GLKeyBoard中添加點東西
//鍵盤點擊類型
typedef NS_ENUM(NSInteger,GLKeyBoardType) {
    GLKeyBoardClearAll,
    GLKeyBoardDelete,
    GLKeyBoardOther
};
//鍵盤點擊事件
typedef void(^KeyBoardClickBlcok)(GLKeyBoardType keyBoardType, NSString *text);

這樣后,我們在點擊處就可以添加下面的代碼了

-(void)keyBoardClick:(UIButton *)sender
{
    NSInteger tag = sender.tag - kKeyBoardTag;
    switch (tag) {
        case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:case 11:case 12:case 13:
        {
            if (self.keyBoardClickBlock) {
                self.keyBoardClickBlock(GLKeyBoardOther, sender.currentTitle);
            }
        }
            break;
        case 14:
        {
            if (self.keyBoardClickBlock) {
                self.keyBoardClickBlock(GLKeyBoardDelete, sender.currentTitle);
            }
        }
            break;
        case 15:{
            if (self.keyBoardClickBlock) {
                self.keyBoardClickBlock(GLKeyBoardClearAll, sender.currentTitle);
            }
        }
            break;
        default:
            break;
    }
}

然后我們就可以在block中對textField中進行值的處理了
一開始,我想的是在viewcontroller中,直接添加處理方法,根據按鈕的類型,來改變值,但是這樣的話,豈不是每個用到的地方都要寫一篇,難免太復雜,于是我想到了category,這就有了UITextField+GLKeyBoard這個類的誕生
在該類中主要添加了一個方法
- (void)updateText:(NSString *)text,根據按鈕點擊的文字來更改輸入控件的值,方法過程也不是很復雜,每個地方都有標注,相信大家看了都會明白
最主要的思想就是根據光標來分割兩邊的字符,然后將新的字符插入到光標位置,并移動光標的位置。

- (void)updateText:(NSString *)text
{
    if ([text isEqualToString:@"千"]) {
        [self changeTextWithNumber:1000];
    }else if ([text isEqualToString:@"萬"]){
        [self changeTextWithNumber:10000];
    }else if ([text isEqualToString:@"十萬"]){
        [self changeTextWithNumber:100000];
    }else if ([text isEqualToString:@"百萬"]){
        [self changeTextWithNumber:1000000];
    }
    else{
        UITextPosition *beginning = self.beginningOfDocument;//文字的開始地方
        UITextPosition *startPosition = self.selectedTextRange.start;//光標開始位置
        UITextPosition *endPosition = self.selectedTextRange.end;//光標結束位置
        NSInteger startIndex = [self offsetFromPosition:beginning toPosition:startPosition];//獲取光標開始位置在文字中所在的index
        NSInteger endIndex = [self offsetFromPosition:beginning toPosition:endPosition];//獲取光標結束位置在文字中所在的index
        
        // 將輸入框中的文字分成兩部分,生成新字符串,判斷新字符串是否滿足要求
        NSString *originText = self.text;
        NSString *beforeString = [originText substringToIndex:startIndex];//從起始位置到當前index
        NSString *afterString = [originText substringFromIndex:endIndex];//從光標結束位置到末尾
        
        NSInteger offset;
        
        if (![text isEqualToString:@""]) {
            offset = text.length;
        } else {
            // 只刪除一個字符
            if (startIndex == endIndex) {
                if (startIndex == 0) {
                    return;
                }
                offset = -1;
                beforeString = [beforeString substringToIndex:(beforeString.length - 1)];
            } else {
                //光標選中多個
                offset = 0;
            }
        }
        
        NSString *newText = [NSString stringWithFormat:@"%@%@%@", beforeString, text, afterString];
        self.text = newText;
        
        // 重置光標位置
        UITextPosition *nowPosition = [self positionFromPosition:startPosition offset:offset];
        UITextRange *range = [self textRangeFromPosition:nowPosition toPosition:nowPosition];
        self.selectedTextRange = range;
    }
}

到此為止,我們的鍵盤就OK啦,來看看效果

init.png

嗯哼,怎么感覺不對呢?

  1. 位置不對
  2. 鍵盤上面怎么多了一截呢?

排查后,才發現是導入了IQKeyboard這個類,導致鍵盤默認會有個工具欄在上面,但是我們美工妹子說了,不能要,好吧,于是我查看API,發現了這個參數

/**
 Automatic add IQToolbar functionality. Default is YES.
 */
@property(nonatomic, assign, getter = isEnableAutoToolbar) BOOL enableAutoToolbar;

于是我添加了一行代碼,在vc

   //如果不需要
  [[IQKeyboardManager sharedManager] setEnableAutoToolbar:NO];

瞬間就對了,那么第一個問題怎么辦呢?我首先想到的就是在鍵盤彈出的時候去修改坐標,但是我們必須的拿到這個鍵盤的view,我顯示把GLKeyBoard *keyBoard這個對象當作鍵盤來設置,然后當頭一棒,不行的,完全沒反應。
看來只能自己寫個方法來查找我們自定義的keyBoard

- (UIView *)findKeyboard
{
    UIView *keyboardView = nil;
    NSArray *windows = [[UIApplication sharedApplication] windows];
    for (UIWindow *window in [windows reverseObjectEnumerator])//逆序效率更高,因為鍵盤總在上方
    {
        keyboardView = [self findKeyboardInView:window];
        if (keyboardView)
        {
            return keyboardView;
        }
    }
    return nil;
}

- (UIView *)findKeyboardInView:(UIView *)view
{
    for (UIView *subView in [view subviews])
    {
        NSLog(@" 打印信息:%s",object_getClassName(subView));
        if (strstr(object_getClassName(subView), "UIInputSetHostView"))
        {
            return subView;
        }
        else
        {
            UIView *tempView = [self findKeyboardInView:subView];
            if (tempView)
            {
                return tempView;
            }
        }
    }
    return nil;
}

這里有個問題要注意下,就是如果你不曉得哪個是我們的keyBoard,可以在NSLog(@" 打印信息:%s",object_getClassName(subView));這個位置打個斷點,看看view具體展示的是那個

point.png

網上有這樣的
if (strstr(object_getClassName(subView), "UIKeyboard")),經測試是不行的,我估計應該是在后面的版本中發生了變化
在找到keyBoard這個view后,一切就變的簡單了
我們只需要在鍵盤即將彈出的通知處添加下面代碼就搞定啦

//鍵盤出現時候調用的事件
-(void) keyboadWillShow:(NSNotification *)note{
    NSDictionary *info = [note userInfo];
    CGRect keyboardFrame = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];//鍵盤的frame

    keyboardFrame.origin.y = CGRectGetMaxY(_textFiled.frame) + 4.5;
    UIView *keyBoardView = [self findKeyboard];
    
    
    [UIView animateWithDuration:0.2 animations:^{
        [keyBoardView setFrame:keyboardFrame];
    }];
}

在這里,還遇到個小坑,就是如果textField是寫在cell中的,那么添加通知,最好不要在cell的初始化方法中添加,建議在textField的代理textFieldDidBeginEditing中添加,因為通知是一對多的,如果在cell的初始化方法中添加,當有很多cell的時候,鍵盤會上下跳動,而且坐標不是你想要的坐標

結語

關于自定義鍵盤,就差不多這么,希望大家能喜歡,要放假了,祝大家端午快樂~回家包包子去了....

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容