inputAccessoryView属性存在于UITextView和UITextField两个控件类中,它接收一个自定义view,通过它我们可以很方便的在键盘上扩展我们想要的功能。
先上代码:新建一个project然后运行下面这段代码
UITextField *tf = [[UITextField alloc]initWithFrame:CGRectMake(20.0, 20.0, self.view.bounds.size.width - 40.0, 30.0)];
_tf = tf;
tf.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:tf];
结果:
嗯,这是iOS系统自带键盘,现在我们使用UITextView的inputAccessoryView这个属性来对键盘做一下拓展,以满足我们的需求:
在先前的代码上添加下面的代码:
tf.inputAccessoryView = [self keyboardToolView];
- (UIView *)keyboardToolView {
UIView *kbTView = [[UIView alloc]initWithFrame:CGRectMake(0.0, 0.0, CGRectGetWidth([UIScreen mainScreen].bounds), 40.0)];
kbTView.backgroundColor = [UIColor blackColor];
UIButton *finishBut = [UIButton buttonWithType:UIButtonTypeCustom];
finishBut.frame = CGRectMake(CGRectGetWidth(kbTView.frame) - 60.0, 5.0, 50.0, 30.0);
[finishBut setTitle:@"完成" forState:UIControlStateNormal];
finishBut.layer.borderWidth = 1.0;
finishBut.layer.borderColor = [[UIColor whiteColor]CGColor];;
finishBut.layer.masksToBounds = YES;
finishBut.layer.cornerRadius = 5.0;
[kbTView addSubview:finishBut];
[finishBut addTarget:self action:@selector(keyboardDismiss) forControlEvents:UIControlEventTouchUpInside];
return kbTView;
}
- (void)keyboardDismiss {
[_tf resignFirstResponder];
}
然后我们再次运行:
我们在键盘上面添加了一个“完成”按钮,编辑完成后可以按下这个按钮来关闭键盘。