一行代码为UITextField添加收键盘功能
iOS开发中收键盘是十分常用的功能,只需一行代码即可为ViewController添加工具条收键盘功能
更重要的是使用catogory,无代码污染。
代码
// UITextField+keyboard.h // TextFieldKeyBord // // Created by luo.h on 15/10/8. // Copyright © 2015年 l.h. All rights reserved. // #import <UIKit/UIKit.h> @interface UITextField (keyboard) +(void)registerTextFieldInView:(UIView *)aView; @end
// // UITextField+keyboard.m // TextFieldKeyBord // // Created by luo.h on 15/10/8. // Copyright © 2015年 l.h. All rights reserved. // #import "UITextField+keyboard.h" @implementation UITextField (keyboard) -(void)addToolbarWitDoneTitle:(NSString*)title { UIBarButtonItem *flexibleSpaceLeft = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStyleDone target:self action:@selector(dismissKeyBord)]; [doneButton setTintColor:[UIColor redColor]]; UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.window.frame.size.width, 44.0)]; [toolbar setItems:@[flexibleSpaceLeft, doneButton]]; [self setInputAccessoryView:toolbar]; } //查找所有UITextField并添加按钮 +(void)registerTextFieldInView:(UIView *)aView; { for (id obj in aView.subviews) { NSLog(@"obj class: %@",[obj class]); if ([obj isKindOfClass:[UITextField class]]) { UITextField* theTextField = (UITextField*)obj; [theTextField addToolbarWitDoneTitle:@"完成"]; } } } -(void)dismissKeyBord { [self resignFirstResponder]; } @end
使用:
- (void)viewDidLoad { [super viewDidLoad]; //注册self.view里所有UITextField [UITextField registerTextFieldInView:self.view]; }
Demo: https://files.cnblogs.com/files/sixindev/TextFieldKeyBord.zip
作者:SIBU iOS DEV
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.