iOS 在数字键盘上添加按钮

项目中的一个需求选择数量不使用选择器,而是使用数字键盘上面带确定按钮,做了一些调研把这个功能完成了,没能够把这个功能封装起来用很是不足,希望有人看到这篇博客去实现。

创建一个放在数字键盘上的Button

Button在- (void)viewDidLoad方法里就要初始化,这块让我觉的这么做很low,本来想封装一个继承UITextField的类,Button的什么都封装在里,但会有一些bug,每次键盘弹出时,Button总不能做到与键盘同步,所以就这么做了。

// 键盘按钮
    CGFloat btnH = 0;
    if (kScreenWidth == 320 || kScreenWidth == 375) {
        btnH = 160;
    }else if (kScreenWidth == 414){
        btnH = 169;
    }
    self.doneInKeyboardButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.doneInKeyboardButton.backgroundColor = kMainUIColor;
    [self.doneInKeyboardButton setTitle:@"确定" forState:UIControlStateNormal];
    [self.doneInKeyboardButton addTarget:self action:@selector(doneInKeyboardButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.doneInKeyboardButton .frame = CGRectMake(0, kScreenHeight,kScreenWidth/3-2 , btnH / 3);

变量btnH是Button要根据手机的尺寸做适配。Button的点击方法是点击后要做的业务逻辑。

键盘监听
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}

- (void)handleKeyboardWillShow:(NSNotification *)notification{
    
    NSUInteger  cnt = [[UIApplication  sharedApplication ]  windows ].count;
// 获得UIWindow 层
    UIWindow  * keyboardWindow = [[[UIApplication  sharedApplication ]  windows ]  objectAtIndex:cnt - 1];
    [keyboardWindow addSubview:self.doneInKeyboardButton];
    
    NSDictionary *info = [notification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    
    [UIView animateWithDuration:0.25 animations:^{
        self.doneInKeyboardButton.frame= CGRectMake(0, kScreenHeight - self.doneInKeyboardButton.height, self.doneInKeyboardButton.width , self.doneInKeyboardButton.height);
    }];   
}

- (void)handleKeyboardWillHide:(NSNotification *)notification{
    [UIView animateWithDuration:0.25 animations:^{
        self.doneInKeyboardButton.frame= CGRectMake(0, kScreenHeight, self.doneInKeyboardButton.width , self.doneInKeyboardButton.height);
    }];
}

大体的代码就是这些,其它的就是UITextField的处理了,还有需要优化的地方,希望大家一起说说。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容