gtts微薄

通用方法解决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];
9 }

 



posted @ 2012-02-12 13:01  gtts  阅读(528)  评论(0编辑  收藏  举报