iOS小技巧--给数字键盘加个收起功能

有些时候 没用到第三方,但是一些地方需要用数字键盘, 那么收起数字键盘的触发点可能会不知道在哪里触发了... 下面是给UITextFild加两个方法. 可以根据实际情况调用.

调用如下:

//如果你仅仅是点完成时 收起键盘 可以这样写
 [self.textFild addToolSender]; 
//如果你想在点完成时 还有其他事要做可以这样写
  WeakSelf
  [self.textFild addToolSenderWithBlock:^{
       [weakSelf.textFild resignFirstResponder];
  }];

//#define WeakSelf  __weak typeof(self) weakSelf = self;
iOS小技巧--给数字键盘加个收起功能_第1张图片
f7e198e76aba4c301e062a990885e83c.jpg
iOS小技巧--给数字键盘加个收起功能_第2张图片
屏幕快照 2016-08-23 09.29.00.png

代码如下 :

static const char kBlockActionKey;
@interface UITextField (InputSender)

-(void)addToolSender; 
-(void)addToolSenderWithBlock:(void(^)())block;

@end

@implementation UITextField (InputSender)

-(void)addToolSender{
    
    UIToolbar * topView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
    [topView setBarStyle:UIBarStyleDefault];
    UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(2, 5, 50, 25);
    [btn addTarget:self action:@selector(resignFirstResponder) forControlEvents:UIControlEventTouchUpInside];
    [btn setTitle:@"完成" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc]initWithCustomView:btn];
    NSArray * buttonsArray = [NSArray arrayWithObjects:btnSpace,doneBtn,nil];
    [topView setItems:buttonsArray];
    
    self.inputAccessoryView = topView;
}

-(void)addToolSenderWithBlock:(void(^)())block{
    
    UIToolbar * topView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
    [topView setBarStyle:UIBarStyleDefault];
    UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(2, 5, 50, 25);
    [btn addTarget:self action:@selector(resignFirstResponderAction) forControlEvents:UIControlEventTouchUpInside];
    [btn setTitle:@"完成" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc]initWithCustomView:btn];
    NSArray * buttonsArray = [NSArray arrayWithObjects:btnSpace,doneBtn,nil];
    [topView setItems:buttonsArray];
 
    if (block && !objc_getAssociatedObject(self, &kBlockActionKey)) {
        objc_setAssociatedObject(self, &kBlockActionKey, block, OBJC_ASSOCIATION_COPY);
    }
    self.inputAccessoryView = topView;
}
-(void)resignFirstResponderAction{

    void(^block)() = objc_getAssociatedObject(self, &kBlockActionKey);

    if (block) {
        block();
    }
    
}

@end

你可能感兴趣的:(iOS小技巧--给数字键盘加个收起功能)