Screen shot 2009-11-09 at 8.12.11 AM copy

 

这个简单的教程将介绍怎样在UIAlertView中加入UITextField。它只包括几行代码。你将学到CGAffineTransform和UITextField编程。

 


这是截屏。

Screen shot 2009-11-09 at 8.12.11 AM

 

我们开始吧…

1. 建立一个新的View Based项目。
你可以随意为其取名,我为其命名为TextFieldInAlert。

2. 代码
在viewcontroller.m或TextFieldInAlert.m(如果你命名为TextFieldInAlert的话),然后找到-(void)viewDidLoad 方法。取消其注释加入代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
- (void)viewDidLoad {

    [super viewDidLoad];

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Enter Name Here”
        message:@”this gets covered!” delegate:self
        cancelButtonTitle:@”Dismiss” otherButtonTitles:@”OK!”, nil];

    UITextField *myTextField = [[UITextField alloc]
        initWithFrame:CGRectMake(12, 45, 260, 25)];

    [myTextField setBackgroundColor:[UIColor whiteColor]];

    [alert addSubview:myTextField];

    [alert show];

    [alert release];
    [myTextField release];

}

 

我们做的是调用UIAlertView然后添加一个UITextField。 你可能注意到了UIAlertView的message部分,我们为其赋值为“this gets covered!”,如果我们不为其加上这个语句,那么alert的按钮会更靠上而弄乱UITextField。你可以试一下拿掉这一行看看会发生什么。现在UITextField 出现在UIAlertView中间了。试一下在UITextField输入点什么。噢,为什么键盘盖住了UIAlertView?有一个简单的修正方法。只需加入两行代码就可修正这个问题。加入代码:

1
2
3
    CGAffineTransform myTransform = CGAffineTransformMakeTranslation(0, 60);

    [alert setTransform:myTransform];

 

完整代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Enter Name Here”
        message:@”this gets covered!” delegate:self
        cancelButtonTitle:@”Dismiss” otherButtonTitles:@”OK!”, nil];

    UITextField *myTextField = [[UITextField alloc] initWithFrame:CGRectMake(12, 45, 260, 25)];

    CGAffineTransform myTransform = CGAffineTransformMakeTranslation(0, 60);

    [alert setTransform:myTransform];

    [myTextField setBackgroundColor:[UIColor whiteColor]];

    [alert addSubview:myTextField];

    [alert show];

    [alert release];

    [myTextField release];

 

现在你按下“Build and Run”,你会注意到UITextField将在显示略高一点的位置,当你在UITextField输入时,键盘不会再盖住。这就是CGAffineTransform的作用。这里还有一个视频教程。源代码如下。

 

iPhone Tutorial – UITextField In A UIAlertView

 

原文见:iPhone Coding Tutorial – Inserting A UITextField In A UIAlertView