iPhone SDK开发:自定义UIAlertView
iPhone SDK开发:自定义UIAlertView February 25th, 2009 |
iPhone SDK提供 UIAlertView用以显示消息框, 默认的消息框很简单,只需要提供title和message 以及button按钮即可, 而且默认情况下素有的text是居中对齐的。 那如果需要将文本向左对齐或者添加其他控件比如输入框时该怎么办呢? 不用担心, iPhone SDK还是很灵活的, 有很多delegate消息供调用程序使用。 所要做的就是在
- (void)willPresentAlertView:(UIAlertView *)alertView
中按照自己的需要修改或添加即可, 比如需要将消息文本左对齐,下面的代码即可实现
? View Code OBJC
1
2
3
4
5
6
7
8
9
10
11
12
13
| - (void)willPresentAlertView:(UIAlertView *)alertView
{
for( UIView * view in alertView.subviews )
{
if( [view isKindOfClass:[UILabel class]] )
{
UILabel* label = (UILabel*) view;
label.textAlignment = UITextAlignmentLeft;
}
}
}
|
这段代码很简单, 就是在消息框即将弹出时,遍历所有消息框对象,将其文本对齐属性修改为 UITextAlignmentLeft即可。
添加其他部件也如出一辙, 如下代码添加两个UITextField
? View Code OBJC
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
| - (void)willPresentAlertView:(UIAlertView *)alertView
{
CGRect frame = alertView.frame;
if( alertView==twitterAlertView )
{
frame.origin.y -= 120;
frame.size.height += 80;
alertView.frame = frame;
for( UIView * view in alertView.subviews )
{
if( ![view isKindOfClass:[UILabel class]] )
{
CGRect btnFrame = view.frame;
btnFrame.origin.y += 70;
view.frame = btnFrame;
}
}
UITextField* accoutName = [[HelperClass createTextField] autorelease];//这里创建一个UITextField对象
UITextField* accoutPassword = [[HelperClass createTextField] autorelease];//这里创建一个UITextField对象
accoutName.frame = CGRectMake( 10, 40,frame.size.width - 20, 30 );
accoutPassword.frame = CGRectMake( 10, 80,frame.size.width -20, 30 );
accoutName.placeholder = @"Account Name";
accoutPassword.placeholder = @"Password";
accoutPassword.secureTextEntry = YES;
[alertView addSubview:accoutPassword];
[alertView addSubview:accoutName];
}
}
|
显示将消息框固有的button和label移位, 不然添加的text field会将其遮盖住。 然后添加需要的部件到相应的位置即可。
对于UIActionSheet其实也是一样的, 在
- (void)willPresentActionSheet:(UIActionSheet *)actionSheet
中做同样的处理一样可以得到自己想要的界面。