iOS开发:自定义数字键盘(两种方式)

有的app要求校验身份证号,键盘只能输入数字和X符号,所以要定制键盘,目前有两种方法。


预览




思路

  • 两种方法,一种是改造系统键盘在上面添加button,另一种是全自定义键盘
  • 自定义委托protocal,实现在主view里面可以响应子view的事件

1 改造系统键盘

初始化键盘为数字类型
    //initalize the first textField
    self.idCardNumberSystemModify = [[UITextField alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2 - 140, 100, 280, 30)];
    [_idCardNumberSystemModify setBorderStyle:UITextBorderStyleRoundedRect];
    [_idCardNumberSystemModify setKeyboardType:UIKeyboardTypeNumberPad];
    [_idCardNumberSystemModify setTextAlignment:UITextAlignmentLeft];
    [_idCardNumberSystemModify setPlaceholder:@"input ID with modified keyboard"];
    [_idCardNumberSystemModify setClearButtonMode:UITextFieldViewModeWhileEditing];
    [self.view addSubview:self.idCardNumberSystemModify];
    [_idCardNumberSystemModify setDelegate:self];
添加XButton以及事件响应,并且在编辑框结束编辑时移除
#pragma mark - modify method:add button and callback

- (void)addXButtonToKeyboard
{
    [self addXButtonToKeyboardWithSelector:@selector(onXButtonClicked)
                     normalImg:[UIImage imageNamed:@"Xbutton_normal.png"]
                  highlightImg:[UIImage imageNamed:@"Xbutton_highlight.png"]];

}

- (void)addXButtonToKeyboardWithSelector:(SEL)button_callback normalImg:(UIImage *)normal_icon highlightImg:(UIImage *)highlight_icon
{
    //create the XButton
    UIButton *xButton = [UIButton buttonWithType:UIButtonTypeCustom];
    xButton.tag = XBUTTON_MODIFY_TAG;
    xButton.frame = CGRectMake(0, 0, KEY_WIDTH, KEY_HEIGHT); //the half size of the original image
    xButton.adjustsImageWhenDisabled = NO;
    
    [xButton setImage:normal_icon forState:UIControlStateNormal];
    [xButton setImage:highlight_icon forState:UIControlStateHighlighted];
    [xButton addTarget:self action:button_callback forControlEvents:UIControlEventTouchUpInside];
    
    //add to keyboard
    int cnt = [[UIApplication sharedApplication] windows].count;
    UIWindow *keyboardWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:cnt - 1];
    xButton.frame = CGRectMake(0, keyboardWindow.frame.size.height - KEY_HEIGHT, KEY_WIDTH, KEY_HEIGHT);
    [keyboardWindow addSubview:xButton];
    
}

//when XButton clicked, textField add 'X' char
- (void)onXButtonClicked
{
    self.idCardNumberSystemModify.text = [_idCardNumberSystemModify.text stringByAppendingString:@"X"];
}

//remove XButton from keyboard when the keyboard hide
- (void)removeXButtonFromKeyBoard
{
    int cnt = [[UIApplication sharedApplication] windows].count;
    UIWindow *keyboardWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:cnt - 1];
    [[keyboardWindow viewWithTag:XBUTTON_MODIFY_TAG] removeFromSuperview];
}

2 全自定义键盘

定义一个view类作为新键盘
//
//  NumberKeyboardView.h
//  IdNumberInput
//
//  Created by yxhe on 16/5/9.
//  Copyright © 2016年 yxhe. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@class NumberKeyboardView;

//the defined numberPad delegate
@protocol NumberKeyBoardViewDelegate<NSObject>

@optional

- (void)keyboard:(NumberKeyboardView *)keyboard didClickButton:(UIButton *)textBtn withFieldString:(NSMutableString *)string;

@end


//numberPad view
@interface NumberKeyboardView:UIView

@property (nonatomic, assign) id<NumberKeyBoardViewDelegate> delegate;
@property (nonatomic, strong) NSMutableString *string;

@end

//
//  NumberKeyboardView.m
//  IdNumberInput
//
//  Created by yxhe on 16/5/9.
//  Copyright © 2016年 yxhe. All rights reserved.
//

#import "NumberKeyboardView.h"
#import "ViewController.h"

#define KEYBOARD_HEIGHT 216

#define SCREEN_SIZE [UIScreen mainScreen].bounds.size

@implementation NumberKeyboardView

//custom the view init
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self)
    {
        self.frame = CGRectMake(0, SCREEN_SIZE.height - KEYBOARD_HEIGHT, SCREEN_SIZE.width, KEYBOARD_HEIGHT);
        self.string = [NSMutableString string];
        self.backgroundColor = [UIColor grayColor];
     
        //initialize the keyboard
        [self createButtons];
        
    }
    return self;
}

//add button to the defined keyboard view
- (UIButton *)addButtonWithTitle:(NSString *)title frame:(CGRect)frame_rect image:(UIImage *)normal_image highImage:(UIImage *)high_image
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:frame_rect];
//    button.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setBackgroundImage:normal_image forState:UIControlStateNormal];
    [button setBackgroundImage:high_image forState:UIControlStateHighlighted];
    
    return button;
}

//create all the buttons
- (void)createButtons
{
    //set the key titles
    NSArray *titleArray = [[NSArray alloc] initWithObjects:@"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", @"X", @"0", @"delete", nil];
    
    //design the keyboard
    int index = 0;
    float button_width = (SCREEN_SIZE.width - 30)/3;
    float button_height = (KEYBOARD_HEIGHT - 40)/4;
    
    
    for(int i = 0; i < 4; i++)
        for(int j = 0; j < 3; j++)
        {
            float x = 5 + j*(button_width + 10);
            float y = 5 + i*(button_height + 10);
            
            UIButton *button = [self addButtonWithTitle:titleArray[index] frame:CGRectMake(x, y, button_width, button_height) image:nil highImage:[UIImage imageNamed:@"bgcolor.png"]];
            [button addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
            [button setBackgroundColor:[UIColor whiteColor]];
            [self addSubview:button];
            
            index++;
        }
}

//button callback
- (void)onClick:(UIButton *)button
{
    //respond to local button events
    if([button.currentTitle isEqualToString:@"delete"] && self.string > 0)
        [self.string deleteCharactersInRange:NSMakeRange(self.string.length-1, 1)];
    else
        [self.string appendString:button.currentTitle];
    
    //call the delegate, first make sure it can respond to selector, then do the delegate method
    if ([self.delegate respondsToSelector:@selector(keyboard:didClickButton:withFieldString:)])
        [self.delegate keyboard:self didClickButton:button withFieldString:self.string];
}

@end
创建一个view类,在里面定义一个委托,这个view持有一个string,通过委托函数实现view里面的编辑和主view里面的编辑框string挂钩,使得主view能够响应这个键盘view的button事件。

编辑框的输入view设置位自己定义的键盘
    //initalize the second textField
    _idCardNumberSelfDefine = [[UITextField alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2 - 140, 200, 280, 30)];
    [_idCardNumberSelfDefine setBorderStyle:UITextBorderStyleRoundedRect];
    [_idCardNumberSelfDefine setTextAlignment:UITextAlignmentLeft];
    [_idCardNumberSelfDefine setPlaceholder:@"input ID with defined keyboard"];
    [_idCardNumberSelfDefine setClearButtonMode:UITextFieldViewModeWhileEditing];
    [self.view addSubview:_idCardNumberSelfDefine];
    [_idCardNumberSelfDefine setDelegate:self];
    
    //intialize the defined keyboardview
    self.numberKeyboard = [[NumberKeyboardView alloc] init];
    self.numberKeyboard.delegate = self;
    
    _idCardNumberSelfDefine.inputView = self.numberKeyboard; //replace the input keyboard with selfdefined keypad

在主view里面实现委托
#pragma mark - define method: callbacks
- (void)keyboard:(NumberKeyboardView *)keyboard didClickButton:(UIButton *)textBtn withFieldString:(NSMutableString *)string
{
    _idCardNumberSelfDefine.text = string;
    NSLog(@"defined keyboard button clicked");
}



#pragma mark - submit button event
- (void)onSubmitBtnClicked
{
    NSLog(@"cardnumber system modify: %@", _idCardNumberSystemModify.text);
    NSLog(@"cardnumber self define: %@", _idCardNumberSelfDefine.text);
    [self.idCardNumberSystemModify resignFirstResponder];
    [self.idCardNumberSelfDefine resignFirstResponder];
}

源代码下载

csdn: 数字键盘自定义
github: IdNumberInput

你可能感兴趣的:(ios)