1.inputAccessoryView
-
UITextFields和UITextViews有一个inputAccessoryView的属性,当你想在键盘上展示一个自定义的view时,你就可以设置该属性。你设置的view就会自动和键盘keyboard一起显示了。
-
需要注意的是,你所自定义的view既不应该处在其他的视图层里,也不应该成为其他视图的子视图。其实也就是说,你所自定义的view只需要赋给属性inputAccessoryView就可以了,不要再做其他多余的操作。
-
我们在使用UITextView和UITextField的时候,可以通过它们的inputAccessoryView属性给输入时呼出的键盘加一个附属视图,通常是工具条,用来丰富键盘的使用
2.inputView
-
inputView就是显示键盘的view,如果重写这个view则不再弹出键盘,而是弹出自己的view.如果想实现当某一控件变为第一响应者时不弹出键盘而是弹出我们自定义的界面,那么我们就可以通过修改这个inputView来实现,比如弹出一个日期拾取器。
-
inputView不会随着键盘出现而出现,设置了InputView只会当UITextField或者UITextView变为第一相应者时显示出来,不会显示键盘了。设置了InputAccessoryView,它会随着键盘一起出现并且会显示在键盘的顶端。InutAccessoryView默认为nil
-
#import "ViewController.h"
-
#define SCREEN_BOUNDS [UIScreen mainScreen].bounds
-
@interface ViewController ()
-
@property (nonatomic, strong) UITextField *textField;
-
@property (nonatomic, strong) UIView *customInputView;
-
@property (nonatomic, strong) UIToolbar *customAccessoryView;
-
@end
-
@implementation ViewController
-
- (void)viewDidLoad {
-
[super viewDidLoad];
-
[self loadBaseUI];
-
}
-
- (void)loadBaseUI{
-
[self.view addSubview:self.textField];
-
}
-
- (UITextField *)textField{
-
if (!_textField) {
-
_textField = [[UITextField alloc]initWithFrame:CGRectMake(50, 100, SCREEN_BOUNDS.size.width - 100, 30)];
-
_textField.layer.borderWidth = 1.0;
-
_textField.layer.borderColor = [UIColor lightGrayColor].CGColor;
-
_textField.layer.cornerRadius = 4.0;
-
_textField.placeholder = @"测试";
-
_textField.inputView = self.customInputView;
-
_textField.inputAccessoryView = self.customAccessoryView;
-
}
-
return _textField;
-
}
-
- (UIView *)customInputView{
-
if (!_customInputView) {
-
_customInputView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_BOUNDS.size.width, 220)];
-
_customInputView.backgroundColor = [UIColor lightGrayColor];
-
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, SCREEN_BOUNDS.size.width, 40)];
-
label.textAlignment = NSTextAlignmentCenter;
-
label.text = @"自定义inputView";
-
[_customInputView addSubview:label];
-
}
-
return _customInputView;
-
}
-
- (UIToolbar *)customAccessoryView{
-
if (!_customAccessoryView) {
-
_customAccessoryView = [[UIToolbar alloc]initWithFrame:(CGRect){0,0,SCREEN_BOUNDS.size.width,40}];
-
_customAccessoryView.barTintColor = [UIColor orangeColor];
-
UIBarButtonItem *space = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
-
UIBarButtonItem *finish = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(done)];
-
[_customAccessoryView setItems:@[space,space,finish]];
-
}
-
return _customAccessoryView;
-
}
-
- (void)done{
-
[self.textField resignFirstResponder];
-
}