车牌号码输入框——Label的inputView

效果图

图比较慢..稍等哈.gif

思路

车牌号码输入的部分都是UILabel,每个label显示一个文字。
弹出键盘通过重写UILabel的inputView来实现。

关于inputView

UITextField的两个属性

// Presented when object becomes first responder.  If set to nil, reverts to following responder chain.  If
// set while first responder, will not take effect until reloadInputViews is called.
@property (nullable, readwrite, strong) UIView *inputView;             
@property (nullable, readwrite, strong) UIView *inputAccessoryView;

在UITextField成为默认响应的时候,会弹出系统键盘。如果对这两个控件的inputView属性设置了自定义的view,在其成为第一响应的时候系统键盘将不再弹出,取而代之的是赋值给inputView的那个view。inputAccessoryView是键盘的辅助视图,即键盘上面那部分。同样当对inputAccessoryView设置了自定义view时,键盘弹出的同时,该view会作为辅助视图出现在键盘的上面,和键盘一起弹出。
UILabel也有这两个属性

// Called and presented when object becomes first responder.  Goes up the responder chain.
@property (nullable, nonatomic, readonly, strong) __kindof UIView *inputView NS_AVAILABLE_IOS(3_2);
@property (nullable, nonatomic, readonly, strong) __kindof UIView *inputAccessoryView NS_AVAILABLE_IOS(3_2);

可以看到inputView和inputAccessoryView是只读的。(这次只用到inputView,暂不讨论inputAccessoryView)
要做到点击弹出键盘的效果,就要自定义UILabel,然后重新申明inputView为readwrite的,并重写get方法,这样在UILabel成为第一响应的时候会自动弹出inputView。

部分代码

@interface SingleEnterLabel : UILabel
@property (strong, nonatomic,readwrite) UIView *inputView;
@end
//重写get方法
- (UIView *)inputView{
    if (!_inputView) {
        _inputView = [self creatInputViewWithType:self.inputViewType];
    }
    return _inputView;
}
- (BOOL)canBecomeFirstResponder{
    return YES;
}

使用

        SingleEnterLabel *textLabel = [[SingleEnterLabel alloc]initWithFrame:frame];
        UITapGestureRecognizer *tapLabel = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapLabelClick:)];
        textLabel.userInteractionEnabled = YES;
        tapLabel.numberOfTapsRequired = 1;
        tapLabel.delaysTouchesBegan = YES;
        [textLabel addGestureRecognizer:tapLabel];
- (void)tapLabelClick:(UITapGestureRecognizer *)tap{
    UIView *view = tap.view;
    [view becomeFirstResponder];
}

完整代码下载:LicensePlateNoEnterView

你可能感兴趣的:(车牌号码输入框——Label的inputView)