1. 最簡單的用法
初始化方法:
注意:如果按鈕數超過兩個,將會創建成如下樣子:
如果按鈕數量超出屏幕顯示范圍,則會創建類似tableView的效果。
2. 為UIAlertView添加多個按鈕
message:@"請選擇一個按鈕:"
delegate:nil
cancelButtonTitle:@"取消"
otherButtonTitles:@"按鈕一", @"按鈕二", @"按鈕三",nil];
[alert show];
[alert release];
3. 如何判斷用戶點擊的按鈕
UIAlertView有一個委托(代理)UIAlertViewDelegate ,繼承該委托來實現點擊事件
頭文件:
}
(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;
-(IBAction) buttonPressed;
@end
{
UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
message:@"請選擇一個按鈕:"
delegate:self
cancelButtonTitle:@"取消"
otherButtonTitles:@"按鈕一", @"按鈕二", @"按鈕三",nil];
[alert show];
[alert release];
}
(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString* msg = [[NSString alloc] initWithFormat:@"您按下的第%d個按鈕!",buttonIndex];
UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"提示"
message:msg
delegate:nil
cancelButtonTitle:@"確定"
otherButtonTitles:nil];
[alert show];
[alert release];
[msg release];
}
4. 手動的取消對話框
5. 為UIAlertView添加子視圖
在為UIAlertView對象太添加子視圖的過程中,有點是需要注意的地方,如果刪除按鈕,也就是取消UIAlerView視圖中所有的按鈕的時候,可能會導致整個顯示結構失衡。按鈕占用的空間不會消失,我們也可以理解為這些按鈕沒有真正的刪除,僅僅是他不可見了而已。如果在UIAlertview對象中僅僅用來顯示文本,那么,可以在消息的開頭添加換行符(@"/n)有助于平衡按鈕底部和頂部的空間。
下面的代碼用來演示如何為UIAlertview對象添加子視圖的方法。
message:nil
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:nil];
[alert show];
UIActivityIndicatorView*activeView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activeView.center = CGPointMake(alert.bounds.size.width/2.0f, alert.bounds.size.height-40.0f);
[activeView startAnimating];
[alert addSubview:activeView];
[activeView release];
[alert release];
6. 其他
UIAlertView默認情況下所有的text是居中對齊的。 那如果需要將文本向左對齊或者添加其他控件比如輸入框時該怎么辦呢? 不用擔心, iPhone SDK還是很靈活的, 有很多delegate消息供調用程序使用。 所要做的就是在
{
for( UIView * view in alertView.subviews )
{
if( [view isKindOfClass:[UILabel class]] )
{
UILabel* label = (UILabel*) view;
label.textAlignment=UITextAlignmentLeft;
}
}
}
添加其他部件也如出一轍, 如下代碼添加兩個UITextField:
{
CGRect frame = alertView.frame;
frame.origin.y -= 120;
frame.size.height += 80;
alertView.frame = frame;
for( UIView * viewin alertView.subviews )
{
if( ![viewisKindOfClass:[UILabelclass]] )
{
CGRect btnFrame = view.frame;
btnFrame.origin.y += 70;
view.frame = btnFrame;
}
}
UITextField* accoutName = [[UITextFieldalloc] init];
UITextField* accoutPassword = [[UITextFieldalloc] init];
accoutName.frame = CGRectMake( 10, frame.origin.y + 40,frame.size.width - 20, 30 );
accoutPassword.frame = CGRectMake( 10, frame.origin.y + 80,frame.size.width -20, 30 );
accoutName.placeholder = @"請輸入賬號";
accoutPassword.placeholder = @"請輸入密碼";
accoutPassword.secureTextEntry = YES;
[alertView addSubview:accoutPassword];
[alertView addSubview:accoutName];
[accoutName release];
[accoutPassword release];
}
對于UIActionSheet其實也是一樣的, 在
新聞熱點
疑難解答