标签:
转载学习http://www.cnblogs.com/jerehedu/p/4496421.html
在ios开发中,经常需要输入信息。输入信息有两种方式: UITextField和UITextView。信息输入完成后,需要隐藏键盘,下面为大家介绍几种隐藏键盘的方式。
1、UITextField
遵守协议
@interface ViewController ()<UITextFieldDelegate>
设置代理
myTextfield.delegate=self;
使用代理中的方法
-(BOOL)textFieldShouldReturn:(UITextfield *)textField
{
[myTextField resignFirstRespinder];
return NO;
}
2、UITextView
遵守协议
@interface ViewController ()<UITextViewDelegate>
设置代理
textView.delegate=self;
使用代理中的方法:
-(BOOL)textView:(UITextview *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
if([text isEqualToStringL@"\n"]){
[textView resignFirstResponder];
return NO;
}
return YES;
}
设置按钮
UIToolbar *topView=[[UIToolbar alloc]initWithFrame:CGRectMake(0,0,320,30)];
[topView setBarStyle:UIBarStyleBlack];
UIBarButtoItem *btnSpace=[[UIBarButtonItem alloc]initWihBarButtonSystemItem:
UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem *doneButton=[[UIBarButtonItem alloc]initWithTitle:@"完成" style:
UIBarButtonItemStyleDone tsrget :self action: @swelector(dismissKeyBoard)];
NSArrar * buttonArray=[NSArrar arrayWithPbjects:btnSpace,doneButton,nil];
[topView setItems:buttonArray];
1、UITextField
[myTextField setInputAccessoryView:TopView];
2、UITExtView
[textView setInputAccessoryView:topView];
添加隐藏键盘方法
-(void)dismissKeyBoar
{
[myTextField resignFirstResponder];
[textView resignFirstResponder];
}
在touchesBegan:withEvent:方法中让输入控件放弃第一响应者身份
-(void)touchesBegan:(NSString *)touches withEvent:(UIEvent *)event{
[myTextField resignFirstResponder];
[textView resignFirstReponder];
}
//添加单击手势
UITapGuestureRecognizer *tap=[[UITapGuestureRecognizer alloc]initWithTarget:self action:@selector(dismissKeyBoard)];
tap.numberOfTouchedRequired=1;
tap.numberOfTapsRequired=1;
[self.view addGestureRecgnizer:tap];
//隐藏键盘
-(void)dismissKeyBoard{
[myTextField resigFirstRespinder];
[textView resigFirstRespinder];
}
-(void)touchhesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[self.view endEditing:YES];
}
标签:
原文地址:http://www.cnblogs.com/yesihoang/p/4511742.html