点击按钮弹出键盘或者特定的键盘

问题

  • 有时候我们可能会遇到在开发中有这种需求,点击一个按钮弹出一个键盘,键盘上面如下面:
点击按钮弹出键盘或者特定的键盘_第1张图片
1.gif

解决办法

  • 第一种解决办法:就是先对按钮增加监听事件,然后自定义弹出的键盘界面,当点击的时候,做一个动画键盘界面从下面升起来,点击完成的时候,就做一个动画从上往下移动然后消失。这种方式不难,不过也就费点时间

  • 第二种方法,就比较讨巧一点。思路是这样的
    因为UITextField 和 UITextView 都是可以输入的输入且都有方法可以设置键盘的内容和上面的附属内容分别是下面两个属性

@property (nullable, readwrite, strong) UIView *inputView;    // 设置键盘内容         
@property (nullable, readwrite, strong) UIView *inputAccessoryView;// 设置键盘的附属内容

但UIButton按钮虽然是有这个两个属性,但可惜是可读的属性,所以就没法直接用。但如果我们自定义UIButton ,在UIButton添加一个UITextField的属性就可以用了

自定义按钮

#import 

@interface CustomBtn : UIButton
@property (nonatomic, weak) UITextField *texField;

@end
- (void)awakeFromNib
{
    [super awakeFromNib];
    
    UITextField *texField = [[UITextField alloc] init];
    texField.hidden = YES;
    [self addSubview:texField];
    self.texField = texField;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        UITextField *texField = [[UITextField alloc] init];
        texField.hidden = YES;
        [self addSubview:texField];
        self.texField = texField;
    }
    return self;
}
@end

创建自定义的按钮,并使用

@interface ViewController ()
@property (weak, nonatomic) IBOutlet CustomBtn *timeBtn;
@property (nonatomic, strong) UIDatePicker *datePicker;
@end
    self.timeBtn.texField.inputAccessoryView = keyboardTool;
    self.timeBtn.texField.inputView = self.datePicker;

这样就能达到我们要的效果

你可能感兴趣的:(点击按钮弹出键盘或者特定的键盘)