Chinaunix首页 | 论坛 | 博客
  • 博客访问: 375895
  • 博文数量: 284
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1707
  • 用 户 组: 普通用户
  • 注册时间: 2014-05-14 16:38
文章分类

全部博文(284)

文章存档

2015年(6)

2014年(278)

我的朋友

分类: iOS平台

2014-06-28 15:31:08

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

    - (void)moveView:(UITextField *)textField leaveView:(BOOL)leave  
    {  
        UIView *accessoryView = textField.inputAccessoryView;  
        UIView *inputview     = textField.inputView;  
          
        int textFieldY = 0;  
        int accessoryY = 0;  
        if (accessoryView && inputview)   
        {  
            CGRect accessoryRect = accessoryView.frame;  
            CGRect inputViewRect = inputview.frame;  
            accessoryY = 480 - (accessoryRect.size.height + inputViewRect.size.height);  
        }  
        else if (accessoryView)  
        {  
            CGRect accessoryRect = accessoryView.frame;  
            accessoryY = 480 - (accessoryRect.size.height + 216);  
        }  
        else if (inputview)  
        {  
            CGRect inputViewRect = inputview.frame;  
            accessoryY = 480 -inputViewRect.size.height;  
        }  
        else  
        {  
            accessoryY = 264; //480 - 216;  
        }  
          
          
        CGRect textFieldRect = textField.frame;  
        textFieldY = textFieldRect.origin.y + textFieldRect.size.height + 20;  
          
        int offsetY = textFieldY - accessoryY;  
        if (!leave && offsetY > 0)   
        {  
            int y_offset = -5;  
              
            y_offset += -offsetY;  
              
            CGRect viewFrame = self.view.frame;  
              
            viewFrame.origin.y += y_offset;  
              
            [UIView beginAnimations:nil context:NULL];  
            [UIView setAnimationBeginsFromCurrentState:YES];  
            [UIView setAnimationDuration:0.3];  
            [self.view setFrame:viewFrame];  
            [UIView commitAnimations];  
        }  
        else  
        {  
            CGRect viewFrame = CGRectMake(0, 20, 320, 460);  
              
            [UIView beginAnimations:nil context:NULL];  
            [UIView setAnimationBeginsFromCurrentState:YES];  
            [UIView setAnimationDuration:0.3];  
            [self.view setFrame:viewFrame];  
            [UIView commitAnimations];  
        }  
    }  
2. [代码]用法很简单,在UITextFieldDelegate的两个方法里分别调用一下这个方法就OK了,如下示例:  
    - (void)textFieldDidBeginEditing:(UITextField *)textField  
    {  
            [self moveView:textField leaveView:NO];  
    }  
      
    - (void)textFieldDidEndEditing:(UITextField *)textField;  
    {  
        [self moveView:textField leaveView:YES];  
    }  
阅读(480) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~