實現方法:
1)將輸入框的代理設置為self
(在lb文件中將輸入框的delegate設置為File’s Owner 。或者使用代碼textField.delegate = self;
2)將輸入框所對應的ViewController.h設置實現了UITextFieldDelegate協議
在ViewController.m文件中實現UITextFieldDelegate的三個方法即可:
#pragma -mark UITextField Delegate
-(void)textFieldDidBeginEditing:(UITextField *)textField{
CGRect frame = textField.frame;
int offset = frame.origin.y +32 - (self.view.frame.size.height -216.0);//鍵盤高度216
NSTimeInterval animationDuration = 0.30f;
[UIViewbeginAnimations:@"ResizeForKeyboard"context:nil];
[UIViewsetAnimationDuration:animationDuration];
//將視圖的Y坐標向上移動offset個單位,以使下面騰出地方用於軟鍵盤的顯示
if(offset > 0)
self.view.frame =CGRectMake(0.0f, -offset,self.view.frame.size.width,self.view.frame.size.height);
[UIViewcommitAnimations];
}
//當用戶按下return鍵或者按回車鍵,keyboard消失
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
//輸入框編輯完成以後,將視圖恢復到原始狀態
-(void)textFieldDidEndEditing:(UITextField *)textField
{
self.view.frame =CGRectMake(0,0, self.view.frame.size.width,self.view.frame.size.height);
}
//觸摸view隱藏鍵盤――touchDown
- (IBAction)View_TouchDown:(id)sender {
// 發送resignFirstResponder.
[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
}