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: http://files.cnblogs.com/files/sixindev/TextFieldKeyBord.zip