通用方法解决UITextFiled输入的时候,键盘遮挡问题

来自开心程序


我们在用键盘录入的时候,有可能会遮挡录入框,所以我们应调整UIView的位置,使其不被遮挡。我写了一个通用的方法可以解决这个问题:

  1. - (void)moveView:(UITextField *)textField leaveView:(BOOL)leave  
  2. {  
  3.     UIView *accessoryView = textField.inputAccessoryView;  
  4.     UIView *inputview     = textField.inputView;  
  5.       
  6.     int textFieldY = 0;  
  7.     int accessoryY = 0;  
  8.     if (accessoryView && inputview)   
  9.     {  
  10.         CGRect accessoryRect = accessoryView.frame;  
  11.         CGRect inputViewRect = inputview.frame;  
  12.         accessoryY = 480 - (accessoryRect.size.height + inputViewRect.size.height);  
  13.     }  
  14.     else if (accessoryView)  
  15.     {  
  16.         CGRect accessoryRect = accessoryView.frame;  
  17.         accessoryY = 480 - (accessoryRect.size.height + 216);  
  18.     }  
  19.     else if (inputview)  
  20.     {  
  21.         CGRect inputViewRect = inputview.frame;  
  22.         accessoryY = 480 -inputViewRect.size.height;  
  23.     }  
  24.     else  
  25.     {  
  26.         accessoryY = 264; //480 - 216;  
  27.     }  
  28.       
  29.       
  30.     CGRect textFieldRect = textField.frame;  
  31.     textFieldY = textFieldRect.origin.y + textFieldRect.size.height + 20;  
  32.       
  33.     int offsetY = textFieldY - accessoryY;  
  34.     if (!leave && offsetY > 0)   
  35.     {  
  36.         int y_offset = -5;  
  37.           
  38.         y_offset += -offsetY;  
  39.           
  40.         CGRect viewFrame = self.view.frame;  
  41.           
  42.         viewFrame.origin.y += y_offset;  
  43.           
  44.         [UIView beginAnimations:nil context:NULL];  
  45.         [UIView setAnimationBeginsFromCurrentState:YES];  
  46.         [UIView setAnimationDuration:0.3];  
  47.         [self.view setFrame:viewFrame];  
  48.         [UIView commitAnimations];  
  49.     }  
  50.     else  
  51.     {  
  52.         CGRect viewFrame = CGRectMake(0, 20, 320, 460);  
  53.           
  54.         [UIView beginAnimations:nil context:NULL];  
  55.         [UIView setAnimationBeginsFromCurrentState:YES];  
  56.         [UIView setAnimationDuration:0.3];  
  57.         [self.view setFrame:viewFrame];  
  58.         [UIView commitAnimations];  
  59.     }  
  60. }  

用法很简单,在UITextFieldDelegate的两个方法里分别调用一下这个方法就OK了,如下示例:
  1. - (void)textFieldDidBeginEditing:(UITextField *)textField  
  2. {  
  3.         [self moveView:textField leaveView:NO];  
  4. }  
  5.   
  6. - (void)textFieldDidEndEditing:(UITextField *)textField;  
  7. {  
  8.     [self moveView:textField leaveView:YES];  




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值