前言
對做iOS開發(fā)的程序猿們來說UITextField
肯定很熟悉规辱,在點(diǎn)擊UITextField
后會彈出鍵盤,輸入完之后我們希望鍵盤退出否則會遮擋住界面萨螺,所以我們需要退出鍵盤桐经。其實(shí)現(xiàn)在基本上第三方鍵盤都有這個功能,但是蘋果爸爸的鍵盤并沒有這個功能想许,保不齊哪個用戶喜歡用蘋果爸爸的鍵盤,所以我們還是得實(shí)現(xiàn)這個功能。
簡單的方案點(diǎn)擊鍵盤以外的地方讓鍵盤退出伸刃,但是這種方案在這個界面是TableView
或者當(dāng)前界面存在多個輸入入口時(shí)谎砾,用戶體驗(yàn)不是很好逢倍。所以這種簡單的粗暴的方案不能解決問題捧颅,畢竟用戶是我們爸爸。
所以我們采用第二種方案较雕,在UITextField
彈出鍵盤上加一個按鈕用來退出鍵盤碉哑。
- 方法一:在
UITextField
的代理里復(fù)寫textField
的inputAccessoryView
第一步:在當(dāng)前控制器創(chuàng)建一個View
- (UIView*)customView {
if (!_customView) {
_customView =[[UIView alloc]initWithFrame:CGRectMake(-1, 0, ScreenWidth+2, 40)];
_customView.backgroundColor = UIColorFromRGB(0xd8d8d8);
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth - 55, 5, 40, 28)];
[btn setTitle:@"完成" forState:UIControlStateNormal];
[btn setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateNormal];
btn.titleLabel.font = [UIFont systemFontOfSize:14];
btn.backgroundColor = [UIColor clearColor];
[btn addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];
[_customView addSubview:btn];
}
return _customView;
}
- (void)btnClicked{
[self.view endEditing:YES];
}
第二步:在UITextField
代理方法textFieldShouldBeginEditing:
中復(fù)寫inputAccessoryView
- (BOOL)textFieldShouldBeginEditing:(UITextField*)textField {
textField.inputAccessoryView = self.customView; // 往自定義view中添加各種UI控件(以UIButton為例)
CGRect frame = [self.view convertRect:self.view.bounds fromView:textField];
NSLog(@"%@",NSStringFromCGRect(frame));
return YES;
}
- 方法二:在
textField
的drawRect
方法里繪制
自定義一個textField,繼承與UITextField
亮蒋,然后在其drawRect
方法中繪制一個按鈕
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
UIToolbar *bar = [[UIToolbar alloc] initWithFrame:CGRectMake(0,0, kScreenWidth,44)];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth - 60, 7,50, 30)];
[button setTitle:@"完成"forState:UIControlStateNormal];
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
button.layer.borderColor = [UIColor redColor].CGColor;
button.layer.borderWidth =1;
button.layer.cornerRadius =3;
[bar addSubview:button];
self.inputAccessoryView= bar;
[button addTarget:self action:@selector(print) forControlEvents:UIControlEventTouchUpInside];
}
- (void) print {
NSLog(@"button click”);
[[self superview] endEditing:YES];
}