iOS 自定义键盘

释放双眼,带上耳机,听听看~!

自定义键盘,以UITextField为例,给出两种思路。

第一种:通过UITextField的inputView实现,默认为nil,显示系统键盘,将inputView设置为我们自定义的键盘视图即可。

首先看一下效果图:

下面贴上代码:

ViewController:

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
/*** ---------------分割线--------------- ***/
#import "ViewController.h"
#import "HWKeyboard.h"
@interface ViewController ()<HWKeyboardDelegate>
@property (nonatomic, strong) UITextField *numTextField;
@property (nonatomic, strong) UITextField *passWordTextField;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//创建控件
[self creatControl];
}
- (void)creatControl
{
//数字输入框
_numTextField = [[UITextField alloc] initWithFrame:CGRectMake(50, 100, 200, 44)];
_numTextField.placeholder = @"请输入号码";
_numTextField.borderStyle = UITextBorderStyleRoundedRect;
_numTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
[self.view addSubview:_numTextField];
//数字键盘
HWKeyboard *keyboard = [HWKeyboard keyboardWithTextField:_numTextField];
keyboard.delegate = self;
keyboard.type = HWKeyBoardTypeNext;
_numTextField.inputView = keyboard;
//密码输入框
_passWordTextField = [[UITextField alloc] initWithFrame:CGRectMake(50, 180, 200, 44)];
_passWordTextField.placeholder = @"请输入密码";
_passWordTextField.borderStyle = UITextBorderStyleRoundedRect;
_passWordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
[self.view addSubview:_passWordTextField];
}
#pragma mark - HWKeyboardDelegate
- (void)keyboardEditingChanged:(HWKeyboard *)keyboard
{
NSLog(@"numText:%@", _numTextField.text);
}
- (void)keyboardDoneAction:(HWKeyboard *)keyboard
{
[_numTextField resignFirstResponder];
if (keyboard.type == HWKeyBoardTypeNext) [_passWordTextField becomeFirstResponder];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
}
@end

HWKeyboard:

#import <UIKit/UIKit.h>
@class HWKeyboard;
@protocol HWKeyboardDelegate <NSObject>
- (void)keyboardEditingChanged:(HWKeyboard *)keyboard;
- (void)keyboardDoneAction:(HWKeyboard *)keyboard;
@end
@interface HWKeyboard : UIView
typedef enum {
HWKeyBoardTypeDone = 0,
HWKeyBoardTypeNext,
} type;
@property (nonatomic, assign) NSInteger type;
@property (nonatomic, weak) id<HWKeyboardDelegate> delegate;
+ (instancetype)keyboardWithTextField:(UITextField *)textField;
@end
/*** ---------------分割线--------------- ***/
#import "HWKeyboard.h"
#define KMainW [UIScreen mainScreen].bounds.size.width
#define KMainH [UIScreen mainScreen].bounds.size.height
#define KBtnTag 100
#define KKeyboardH KMainH * 0.252
@interface HWKeyboard ()
@property (nonatomic, strong) UITextField *textField;
@end
@implementation HWKeyboard
//初始化类方法
+ (instancetype)keyboardWithTextField:(UITextField *)textField
{
return [[self alloc] initWithTextField:textField];
}
//私有init方法
- (instancetype)initWithTextField:(UITextField *)textField
{
if (self = [super init]) {
self.textField = textField;
//添加监听
[self.textField addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew context:nil];
}
return self;
}
//监听
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
if ([keyPath isEqualToString:@"text"]) {
if (_delegate && [_delegate respondsToSelector:@selector(keyboardEditingChanged:)]) {
[_delegate keyboardEditingChanged:self];
}
}
}
//移除
- (void)dealloc
{
[self.textField removeObserver:self forKeyPath:@"text"];
}
//重写父类init方法
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
self.frame = CGRectMake(0, 0, KMainW, KKeyboardH);
//创建控件
[self creatControl];
}
return self;
}
//创建控件
- (void)creatControl
{
CGFloat btnW = self.bounds.size.width / 3.0f;
CGFloat btnH = self.bounds.size.height / 4.0f;
int num = 3;
for (int i = 0; i < 12; i ++) {
int row = i / num;
int col = i % num;
CGFloat btnX = btnW * col;
CGFloat btnY = btnH * row;
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(btnX, btnY, btnW, btnH)];
btn.backgroundColor = [UIColor whiteColor];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
btn.layer.borderColor = [[UIColor lightGrayColor] CGColor];
btn.layer.borderWidth = 1.0f;
btn.tag = KBtnTag + i;
[btn setTitle:[NSString stringWithFormat:@"%d", i + 1] forState:UIControlStateNormal];
if (i == 9) {
[btn setTitle:@"删格" forState:UIControlStateNormal];
}else if (i == 10) {
[btn setTitle:[NSString stringWithFormat:@"%d", 0] forState:UIControlStateNormal];
}else if (i == 11) {
[btn setTitle:@"完成" forState:UIControlStateNormal];
}
[btn addTarget:self action:@selector(btnOnClick:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:btn];
}
}
- (void)setType:(NSInteger)type
{
_type = type;
UIButton *btn = (UIButton *)[self viewWithTag:KBtnTag + 11];
if (self.type == HWKeyBoardTypeDone) {
[btn setTitle:@"完成" forState:UIControlStateNormal];
}else if (self.type == HWKeyBoardTypeNext) {
[btn setTitle:@"下一项" forState:UIControlStateNormal];
}
}
//点击事件
- (void)btnOnClick:(UIButton *)btn
{
//获取输入框字符,并转换为可变字符
NSMutableString *str = [_textField.text mutableCopy];
if (!str) str = [NSMutableString string];
//获取光标位置
NSUInteger position = [_textField offsetFromPosition:_textField.beginningOfDocument toPosition:_textField.selectedTextRange.start];
if (!_textField.text && [_textField.text isEqualToString:@""]) position = 0;
if (btn.tag == 9 + KBtnTag) {
//退格键
if (position == 0) return;
position --;
[str deleteCharactersInRange:NSMakeRange(position, 1)];
}else if (btn.tag == 11 + KBtnTag) {
//完成键
if (_delegate && [_delegate respondsToSelector:@selector(keyboardDoneAction:)]) {
[_delegate keyboardDoneAction:self];
}
}else {
//数字键
[str insertString:btn.titleLabel.text atIndex:position];
position ++;
}
//设置文本框文字
_textField.text = str;
//设置光标位置
UITextPosition *currentPosition = [_textField positionFromPosition:[_textField beginningOfDocument] offset:position];
[_textField setSelectedTextRange:[_textField textRangeFromPosition:currentPosition toPosition:currentPosition]];
}
@end

 

第二种:监听系统键盘,在键盘将要显示时获取到键盘视图,在该视图上添加我们自定义的键盘视图即可,这里没有具体实现自定义的键盘,下面贴上获取键盘视图的代码:

#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) UITextField *textField;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//创建控件
[self creatControl];
//添加键盘监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
}
- (void)creatControl
{
//输入框
_textField = [[UITextField alloc]initWithFrame:CGRectMake(50, 100, 200, 44)];
_textField.placeholder = @"请输入号码";
_textField.borderStyle = UITextBorderStyleRoundedRect;
_textField.clearButtonMode = UITextFieldViewModeWhileEditing;
[self.view addSubview:_textField];
}
- (void)keyboardWillShow:(NSNotification *)notification
{
UIView *keyboardView = [self findKeyboard];
UIView *keyboard = [[UIView alloc] initWithFrame:keyboardView.bounds];
keyboard.backgroundColor = [UIColor greenColor];
[keyboardView addSubview: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]) {
if (strstr(object_getClassName(subView), "UIKeyboard")) {
return subView;
}else {
UIView *tempView = [self findKeyboardInView:subView];
if (tempView) {
return tempView;
}
}
}
return nil;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end

写博客的初心是希望大家共同交流成长,博主水平有限难免有偏颇不足之处,欢迎批评指正。

人已赞赏
iOS文章

CocoaPods的安装和使用

2020-2-20 23:24:05

iOS文章

iOS 逆向必备工具和安装过程

2020-2-21 4:36:47

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索