有时候调用苹果手机的系统键盘满足不了现实中的各种需求,因此就需要我们自定义键盘来代替系统原有的键盘
话不多说,直接上代码:
首先代码创建一个输入框或直接在storyboard中拖一个UITextFild来弹出键盘:
_textField = [[UITextField alloc] init]; _textField.frame = CGRectMake(60, 200, 200, 30); _textField.borderStyle = UITextBorderStyleRoundedRect; _textField.keyboardType = UIKeyboardTypeDefault; _textField.autocapitalizationType = UITextAutocapitalizationTypeNone; _textField.tag = 100; _textField.returnKeyType = UIReturnKeyNext; // 自定义键盘 UIImageView *inputView = [self setInputView]; _textField.inputView = inputView; [self.view addSubview:_textField];
这是用自定义的键盘来覆盖原有的键盘
编辑键盘上的按钮:
#pragma mark - 自定义键盘 - (UIImageView *)setInputView{ UIImageView *imageView = [[UIImageView alloc] init]; imageView.userInteractionEnabled = YES; imageView.frame = CGRectMake(0, 0, 320, 200); imageView.backgroundColor = [UIColor grayColor]; // 自定义键盘内容 _emojiArray = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17"]; CGFloat buttonW = 40; CGFloat buttonH = 40; NSInteger numberOfRow = ScreenW / buttonW;//列数 NSInteger numberOfLine = _emojiArray.count / numberOfRow;//行数 if (_emojiArray.count % numberOfRow) { numberOfLine = numberOfLine + 1; } for (int j = 0; j < numberOfLine; j ++) { for (int i = 0; i < numberOfRow; i ++) { if (i + j * numberOfRow < _emojiArray.count) { UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; CGFloat X = 5 + 40 * i; CGFloat Y = 5 + buttonH * j; button.frame = CGRectMake(X, Y, buttonW, buttonH); [button addTarget:self action:@selector(inputViewClick:) forControlEvents:UIControlEventTouchUpInside]; button.tag = i + j * numberOfRow; NSLog(@"button.tag = = = = %ld",button.tag); [button setTitle:[_emojiArray objectAtIndex:button.tag] forState:UIControlStateNormal]; [imageView addSubview:button]; } } } return imageView; }
最后实现键盘上的按钮的实现方法:
- (void)inputViewClick:(UIButton *)button{ NSLog(@"%@",_emojiArray[button.tag]); // 拼接 NSString *str = [NSString stringWithFormat:@"%@%@",_textField.text,_emojiArray[button.tag]]; _textField.text = str; }
系统的键盘在弹出的状态下,点击屏幕的空白处收回键盘,那就需要加入下面这段代码来结束按钮的编辑状态:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ [self.view endEditing:YES]; }
效果如图: