iOS 自定义键盘,带时间选择

今天写了个记录账单的demo,里面需要用到自定义键盘,这里简单的记录一下,先上个gif图


myKeyBoard.gif

新建一个继承UIView的类DCAccountKeyBoard
.h里面

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN
//创建自定义键盘协议
@protocol My_KeyBoardDelegate <NSObject>
//创建协议方法
@required//必须执行的方法
- (void)numberKeyBoard:(NSInteger) number;
- (void)cancelKeyBoard;
- (void)finishKeyBoard;
- (void)periodKeyBoard;
- (void)timeKeyBoard;
@optional//不必须执行方法

@end
@interface DCAccountKeyBoard : UIView
{
@private//私有的协议方法
    id<My_KeyBoardDelegate> _delegate;
}
@property (nonatomic, strong) id<My_KeyBoardDelegate> delegate;
@property (nonatomic,strong) UIButton *timeBtn;
- (id)initWithNumber:(NSNumber *)number;
@end

NS_ASSUME_NONNULL_END

.m里面创建自定义控件,根据自己需要布局

#import "DCAccountKeyBoard.h"
@implementation DCAccountKeyBoard

-(id)initWithNumber:(NSNumber *)number {
    if (self = [super init]) {
        self.backgroundColor = DCColor(244, 245, 244);
        self.frame = CGRectMake(0, ScreenHeight - 150, ScreenHeight, 150);
        [self initKeyBoardNumber_1];
    }
    return self;
}

/**
 setUpUI
 */
- (void)initKeyBoardNumber_1 {
    self.frame=CGRectMake(0, ScreenHeight-bottomSafeHeight-203, ScreenWidth, 203);
    CGFloat kWidth = ScreenWidth/4;
    CGFloat kHeight = 50;
    int space=1;
    
    //number 1-9
    for (int i=0; i<9; i++) {
        NSString *str=[NSString stringWithFormat:@"%d",i+1];
        UIButton *button=[UIButton buttonWithType:UIButtonTypeSystem];
        if (i<3) {
            button.frame=CGRectMake(i%3*kWidth+space,i/3*(kHeight+space), kWidth-space, kHeight);
        }
        else{
            button.frame=CGRectMake(i%3*kWidth+space,i/3*(kHeight+space), kWidth-space, kHeight);
        }
        button.backgroundColor=[UIColor whiteColor];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        button.titleLabel.font=[UIFont systemFontOfSize:24];
        [button setTitle:str forState:UIControlStateNormal];
        button.tag=i+1;
        [button addTarget:self action:@selector(keyBoardAciont:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
    }
    
    //点
    UIButton *dian=[UIButton buttonWithType:UIButtonTypeSystem];
    dian.frame=CGRectMake(space,(kHeight+1)*3 , kWidth-space, kHeight);
    dian.backgroundColor=[UIColor whiteColor];
    [dian setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    dian.titleLabel.font=[UIFont systemFontOfSize:24];
    [dian addTarget:self action:@selector(keyBoardAciont:) forControlEvents:UIControlEventTouchUpInside];
    [dian setTitle:@"." forState:UIControlStateNormal];
    dian.tag=11;
    [self addSubview:dian];
    
    // 0
    UIButton *ling=[UIButton buttonWithType:UIButtonTypeSystem];
    ling.frame=CGRectMake(dian.right+space,dian.y, kWidth-space, kHeight);
    ling.backgroundColor=[UIColor whiteColor];
    [ling setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    ling.titleLabel.font=[UIFont systemFontOfSize:24];
    [ling setTitle:@"0" forState:UIControlStateNormal];
    ling.tag=0;
    [ling addTarget:self action:@selector(keyBoardAciont:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:ling];
    
    //时间按钮
    self.timeBtn=[UIButton buttonWithType:UIButtonTypeSystem];
    self.timeBtn.frame=CGRectMake(kWidth*3+space,0, kWidth-1, kHeight*2+space);
    self.timeBtn.backgroundColor=[UIColor whiteColor];
    [self.timeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.timeBtn setTitle:@"今天" forState:UIControlStateNormal];
    self.timeBtn.tag=12;
    [self.timeBtn addTarget:self action:@selector(keyBoardAciont:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.timeBtn];
    
    //删除键
    UIButton *delete=[UIButton buttonWithType:UIButtonTypeSystem];
    delete.frame=CGRectMake(ling.right+space,ling.y, kWidth-1, kHeight);
    [delete addTarget:self action:@selector(keyBoardAciont:) forControlEvents:UIControlEventTouchUpInside];
    delete.tag=10;
    [delete setImage:IMAGENAME(@"键盘删除") forState:UIControlStateNormal];
    delete.backgroundColor = [UIColor whiteColor];
    [self addSubview:delete];
    
    //完成键
    UIButton *confirm=[UIButton buttonWithType:UIButtonTypeSystem];
    confirm.frame=CGRectMake(delete.right+space,self.timeBtn.bottom+space, kWidth-1, kHeight*2+space);
    confirm.backgroundColor=BlueColor;
    [confirm setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    confirm.titleLabel.font=[UIFont systemFontOfSize:20];
    [confirm setTitle:@"完 成" forState:UIControlStateNormal];
    [confirm addTarget:self action:@selector(keyBoardAciont:) forControlEvents:UIControlEventTouchUpInside];
    confirm.tag=13;
    [self addSubview:confirm];
}
#pragma 键盘点击按钮事件
- (void)keyBoardAciont:(UIButton *)sender {
    UIButton* btn = (UIButton*)sender;
    NSInteger number = btn.tag;
    if (nil == _delegate) {
        DCLog(@"button tag [%ld]",(long)number);
        return;
    }
    
    if (number <=9 && number >= 0) {
        [_delegate numberKeyBoard:number];
        return;
    }
    
    if (number == 10) {
        [_delegate cancelKeyBoard];
        return;
    }
    
    if (11==number) {
        [_delegate periodKeyBoard];
        return;
    }
    
    if (12==number) {
        [_delegate timeKeyBoard];
        return;
    }
    
    if (13==number) {
        [_delegate finishKeyBoard];
        return;
    }
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end

引用自定义键盘
在控制器里面创建一个按钮点击事件,自定义一个UITextField

-(void)setUpInputView {
    self.inputView = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight, ScreenWidth, 40)];
    self.inputView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.inputView];
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 50, 40)];
    titleLabel.text = @"备注:";
    titleLabel.font = FONT(16);
    titleLabel.backgroundColor = [UIColor whiteColor];
    [self.inputView addSubview:titleLabel];
    
    UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(titleLabel.right, 0, self.inputView.width - titleLabel.width - 2, 40)];
    textField.backgroundColor = [UIColor whiteColor];
    textField.text = @"0";
    textField.font = FONT(20);
    self.inputTextField = textField;
    [self.inputView addSubview:textField];
}

点击按钮的时候调用下面的方法

/**
 UIKeyBoardAction--键盘处理
 */
-(void)showKeyBoard {
    [self.inputTextField becomeFirstResponder];
    self.inputTextField.text = nil;
    [self keyBoardTypeAction];
}
- (void)keyBoardTypeAction {
    self.my_keyboard = [[DCAccountKeyBoard alloc] initWithNumber:@1];
    self.inputTextField.inputView = self.my_keyboard;
    self.my_keyboard.delegate = self;
    [self.inputTextField reloadInputViews];
}
- (void)hidenKeyBoard {
    [self.inputTextField resignFirstResponder];
}

键盘的代理方法,按钮点击事件

- (void)numberKeyBoard:(NSInteger)number {
    NSString *str = self.inputTextField.text;
    self.inputTextField.text = [NSString stringWithFormat:@"%@%ld",str,(long)number];
}
- (void)cancelKeyBoard {
    NSMutableString *muStr = [[NSMutableString alloc] initWithString:self.inputTextField.text];
    if (muStr.length <= 0) {
        return;
    }
    [muStr deleteCharactersInRange:NSMakeRange([muStr length] - 1, 1)];
    self.inputTextField.text = muStr;
}
#pragma 输入点
-(void)periodKeyBoard {
    if ([self.inputTextField.text isEqualToString:@""]) {
        return;
    }
    //判断当前时候存在一个点
    if ([self.inputTextField.text rangeOfString:@"."].location == NSNotFound) {
        //输入中没有点
        NSMutableString  *mutableString=[[NSMutableString alloc]initWithFormat:@"%@%@",self.inputTextField.text,@"."];
        self.inputTextField.text=mutableString;
    }
}
-(void)timeKeyBoard {
    [self hidenKeyBoard];
    DCDatePickerView *pickerDate = [[DCDatePickerView alloc]initWithIsisAddYetSelect:NO isShowDay:YES];
    [pickerDate show];
    __weak typeof(self) weakself = self;
    pickerDate.block = ^(NSString *timeString) {
        DCLog(@"timeString%@",timeString);
        [weakself showKeyBoard];
        [weakself.my_keyboard.timeBtn setTitle:timeString forState:UIControlStateNormal];
    };
}
-(void)finishKeyBoard{
    [self hidenKeyBoard];
    DCLog(@"type:%@-money-%@-time:%@",self.selectedTitle,self.inputTextField.text,self.my_keyboard.timeBtn.titleLabel.text);
}

viewDidLoad里面设置通知

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidenKeyBoard)];
    [self.view addGestureRecognizer:tap];
    
    [NOTIFICATION addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [NOTIFICATION addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

// 根据键盘状态,调整_mainView的位置
- (void)keyboardWillShow:(NSNotification *)notification{
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyBoardSize = value.CGRectValue.size;
    self.inputView.frame = CGRectMake(0, ScreenHeight - keyBoardSize.height - 40, ScreenWidth, 40);
}
-(void)keyboardWillHide:(NSNotification *)notification {
    self.inputView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, 40);
}

❗️如果项目中引用了IQKeyboardManagr的话,最好在当前控制器里面设置一下,不然会出现textField和弹出来的键盘直接有个空隙,类似下图

image.png

解决方法:

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[IQKeyboardManager sharedManager] setEnable:NO];
}
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[IQKeyboardManager sharedManager] setEnable:YES];
}

想要demo的童鞋,请移步到demo传送门。。如果帮助到你了,或者喜欢的童鞋请留个✨哦😊😊

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,425评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,058评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,186评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,848评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,249评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,554评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,830评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,536评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,239评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,505评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,004评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,346评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,999评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,060评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,821评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,574评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,480评论 2 267

推荐阅读更多精彩内容

  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    X先生_未知数的X阅读 15,937评论 3 118
  • 当我许久未回家,然后回家之后,我才开始意识到自己身上显现出的一切剩女经典病症,我妈,我婶,我奶奶都在问我,你到底想...
    芸简阅读 156评论 0 0
  • 一直觉得大大的芒果一定会很好吃,可是美丽的外表里面那么大的一个核…好对不起外表金黄的颜色!因为老了! 一直想吃麻辣...
    叶子随笔阅读 151评论 0 0
  • “我愿意守护这颗恶魔果实,只为了梦里都有你的模样~
    美华Angel阅读 173评论 0 0
  • “您是说您有家人?有孩子?”梁满急切的问道,他很想知道答案,他知道,他自己心里的想法有多么不可思议,可他那么多年...
    2班王圯涵11号阅读 511评论 0 1