iOS 自定義數(shù)字鍵盤

在開發(fā)中經(jīng)常碰到一些會用到自定義的數(shù)字鍵盤的,這些一般都是隨機或者按照一定的規(guī)則來生成的數(shù)字鍵盤,這段時間剛好有這個需求所以就寫了一個先看下效果

Untitled.gif

先說一下實現(xiàn)思路:
其實開發(fā)這種鍵盤很簡單的,直接自定義一個UITextField 的 inputView就行了, 這個自定的view上面是一個toolbar 下面則是用的 collectionview 然后處理點擊事件來控制輸入效果

那接下來我們來看一下實現(xiàn)過程:
首先我們先來實現(xiàn)自定義的View

- (void)setupComponents
{
    
    self.bounds = CGRectMake(0, 0, self.bounds.size.width, kKeyBoardHeight);
    
    [self setupToolBar];
    [self setupCollectionView];
}

-(void)setupToolBar
{
    UIToolbar *toolBar = [UIToolbar new];
    toolBar.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self addSubview:toolBar];
    
    
    UIImageView *safeImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"keyboard_safe"]];
    [toolBar addSubview:safeImage];
    
    UILabel *safeLabel = [UILabel new];
    safeLabel.textAlignment = NSTextAlignmentCenter;
    safeLabel.text = @"安全鍵盤";
    safeLabel.textColor = self.fontColor;
    safeLabel.font = [UIFont systemFontOfSize:15];
    [toolBar addSubview:safeLabel];
    
    
    UIBarButtonItem *flexibleBarBtnItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    UIBarButtonItem *finishInputBarBtnItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneBtnClick)];
    toolBar.tintColor = [UIColor blackColor];
    toolBar.items = @[flexibleBarBtnItem, finishInputBarBtnItem];
    
    
    [toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self);
        make.leading.equalTo(self);
        make.trailing.equalTo(self);
        make.height.mas_equalTo(KToolBarViewHeight);
    }];
    
    [safeImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(15.0f, 17.0f));
        make.centerY.equalTo(toolBar);
        make.trailing.equalTo(safeLabel.mas_leading).offset(-6.0f);
    }];
    
    [safeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(CGSizeMake(toolBar.center.x+11.0f, toolBar.center.y));
    }];
}

-(void)setupCollectionView
{
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.minimumInteritemSpacing = self.itemSpace;
    flowLayout.minimumLineSpacing = self.itemSpace;
    flowLayout.sectionInset = UIEdgeInsetsMake(self.itemSpace, 0, -self.itemSpace, 0);
    flowLayout.itemSize = CGSizeMake(kItemWidth, kItemHeight);
    
    _keyboardView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, KToolBarViewHeight, [UIScreen mainScreen].bounds.size.width, self.frame.size.height - KToolBarViewHeight) collectionViewLayout:flowLayout];
    _keyboardView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    _keyboardView.delaysContentTouches = NO;
    _keyboardView.dataSource = self;
    _keyboardView.delegate = self;
    [self addSubview:_keyboardView];
    
    [_keyboardView registerClass:[SafeKeyboardImageCell class] forCellWithReuseIdentifier:NSStringFromClass([SafeKeyboardImageCell class])];
    [_keyboardView registerClass:[SafeKeyboardTextCell class] forCellWithReuseIdentifier:NSStringFromClass([SafeKeyboardTextCell class])];
    
}

這里很簡單就是UI的搭建 用到了masonry來自動布局的,但這里我們是自己添加的toolbar,里面有一個完成按鈕,收鍵盤用的,如果你用到了IQKeyBoardManager等這種鍵盤控制的三方庫的可能需要做一下兼容沒因為他們也自動加了一個toolbar 例如:IQKeyBoardManager

-(void)textFieldBeginEditing
{
    if (randomKeyboard && changeWhenAppear)
    {
        [self refresh];
    }
    //如果用到了IQKeyboardManager
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
}
-(void)textFieldEndEditing
{
    //如果用到了IQKeyboardManager
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
}

接下來就是數(shù)據(jù)源了:
使用隨機排序的數(shù)據(jù)源

- (void)refresh
{
    if (randomKeyboard)
    {
        [_titleArr removeAllObjects];
        NSMutableArray *startArray=[[NSMutableArray alloc] initWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",nil];
        NSMutableArray *resultArray = [[NSMutableArray alloc] initWithCapacity:0];
        NSInteger m = 10;
        for (int i=0; i<m; i++)
        {
            int t=arc4random()%startArray.count;
            resultArray[i] = startArray[t];
            startArray[t] = [startArray lastObject];
            [startArray removeLastObject];
        }
        [resultArray insertObject:@"C" atIndex:9];
        [resultArray insertObject:@"D" atIndex:11];
        _titleArr = resultArray;
    }
    else
    {
        _titleArr = [NSMutableArray arrayWithArray:@[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"C",@"0",@"D"]];
    }
    
    [_keyboardView reloadData];
}

然后處理點擊事件

- (void)showInputWithNumberStr:(NSString *)numStr
{
    
    if ([@"C" isEqualToString:numStr])
    {
        _textField.text = @"";
        _safeKeyboardDidChangedBlock ? _safeKeyboardDidChangedBlock(_textField.text) : nil;
    }
    else if([@"D" isEqualToString:numStr])
    {
        [_textField deleteBackward];
    }
    else
    {
        [_textField insertText:numStr];
    }
}

最后設(shè)置UITextField的inputView為我們自定義的view就OK了

- (instancetype)initWithTextField:(UITextField *)textField
{
    if (self = [super init])
    {
        _textField = textField;
        _textField.inputView = self;
        [_textField addTarget:self action:@selector(textFieldChangedEditing) forControlEvents:UIControlEventEditingChanged];
        [_textField addTarget:self action:@selector(textFieldBeginEditing) forControlEvents:UIControlEventEditingDidBegin];
        [_textField addTarget:self action:@selector(textFieldEndEditing) forControlEvents:UIControlEventEditingDidEnd];
    }
  

控件中已經(jīng)給出2個自定義需求的參數(shù),需要的同學(xué)可以直接修改就行,其中第二個參數(shù)changeWhenAppear這個是表示每次鍵盤出現(xiàn)都隨機排序鍵盤,設(shè)置為NO的話,鍵盤只在實例化的時候隨機一次后面都是按這個隨機排序出現(xiàn)的,你點擊收起再彈出來排序不變

const static BOOL randomKeyboard = YES;//是否使用隨機鍵盤
const static BOOL changeWhenAppear = YES;//每次鍵盤出現(xiàn)都改變隨機(隨機鍵盤才有效)

控件我簡單的封裝了下,需要的小伙伴拿去吧

Demo地址

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 來自產(chǎn)品經(jīng)理的"簡單"需求一則 需求:在輸入身份證號碼的時候,彈出來的鍵盤是能夠切換到字母的九宮格數(shù)字鍵盤。(左邊...
    伊爾今夏閱讀 10,810評論 5 33
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,029評論 25 709
  • 因為項目需求,簡單的弄了個自定義數(shù)字鍵盤 需要的自取,大神勿噴 使用也很簡單 這里是GitHub地址
    _Comma閱讀 950評論 1 2
  • 昨天是6月7日,高考的日子,我在QQ群說了一句話“離我兒子參加高考還有365天”,把大家都逗樂了。 今早看了一篇文...
    三倒拐閱讀 175評論 0 0
  • 如果,我有一對翅膀,我就會努力克服自己怕高的困難。 在高空中,不斷飛翔,把所有的風(fēng)景盡收眼底。 ...
    玉壺冰心之晗嫣閱讀 299評論 0 1

友情鏈接更多精彩內(nèi)容