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
中做同樣的處理一樣可以得到自己想要的界面。