iPhone开发之 UIAlertView

UIAlertView是一个交互性比较好的控件,一般我们可以理解为“弹出框”或者“提示框”,但是在ios里面,有它专用的名字,就是UIAlertView。下面介绍下UIAlertView的使用等情况。本文转自 http://www.999dh.net/article/iphone_ios_art/25.html  转载请说明,谢谢!

1.最简单的一个实例
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Tip" message:@"You Click Me" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil,nil];
    
    [alert show];
    [alert release];
可以看到如下图显示。



2.多个按钮的实例
在 上面的例子中,我们使用了一个按钮,可以看到参数cancelButtonTitle:@"ok" otherButtonTitles:nil。中的 otherButtonTitles 给予的参数是nil,也就是没有其他的按钮,当然你这里可以放更多的按钮,将上面的代码修改如下:
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Tip" message:@"You Click Me" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:@"OK_2",@"OK_3",@"OK_4",nil];

    [alert show];
    [alert release];
可以看到如下图,显示的按钮就一共有4个了。

3. 问题出来了,UIAlertView作为一个提示框,一般情况下只起到“提示”的作用就可以了,也就是只是向用户传达一个消息就可以了,但是如果需要与用 户进行交互式的操作,应该如何操作呢?那这里需要用的是一个UIAlertView的“委托”(delegate):
在头文件里面的代码修改如下:

#import <UIKit/UIKit.h>

@interface CRockViewController : UIViewController<UIAlertViewDelegate>
{

}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;

-(IBAction)buttonPressed:(id)sender;
@end

在源文件里面添加如下两个函数:
-(IBAction)buttonPressed:(id)sender
{

    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Tip" message:@"You Click Me" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:@"OK_2",@"OK_3",@"OK_4",nil];


    [alert show];
    [alert release];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString * msg = [[NSString alloc] initWithFormat:@"You click %d Button" , buttonIndex];
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Tip" message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil , nil ];
    
    [alert show ];
    [alert release];
    [msg release];
}


需要解释一下在buttonPressed 里面 delegate使用的参数是  self,而我们先前使用的是nil。如果需要使用委托的话,一定要将这个参数设置为self,否则是无法正常运行的。

原文地址:https://www.cnblogs.com/rollrock/p/2776161.html