iPhone SDK開發:自定義UIAlertView

iPhone SDK開發:自定義UIAlertView

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章