1.基本用法
1 UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"Test"
2
3
4
5
6
7 nil];
2.多个按钮
取消上面代码@“其他”的注释后,运行效果如下
3.一些系统样式参数
UIAlertViewStyle这个枚举提供了几个样式
1 typedef NS_ENUM(NSInteger, UIAlertViewStyle) {
2
3
4
5
6 };
使用代码如下:
1
2
3
4
5
6
7
8 [view setAlertViewStyle:UIAlertViewStyleLoginAnd
4.判断用户点了哪个按钮
UIAlertView的委托UIAlertViewDelegate ,实现该委托来实现点击事件,如下:
.h文件
1 @interface ViewController : UIViewController {
2
3 }
在.m实现委托的方法
1 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
2 {
3
4
5 }在这个方法中的参数 buttonIndex,表示的是按钮的索引,上图的三按键 “取消”,“确定”,“其他”对应的索引分别为“0”,“1”,“2”.
用Delegate的方式处理点击时候,会带来一个问题比较麻烦,比如在一个页面里,有好几个UIAlertView的时候,处理点击的时候,会增加处理逻辑的复杂度,得做一些判断
这种情况有一个解决办法,就是用Block,添加Block的回调,代替Delegate,target和selector.(下次展开写这个内容)
5.添加子视图
这个用得也是比较多的,贴几个使用实例
添加 UIActivityIndicatorView
实现代码:
10
11
12
13
添加UITableView
这个列表的几行代码也说不清楚,就说下思路吧,UIAlertView之所以有这么大的空间显示UITableView,用了比较取巧的一个办法
1 UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"请选择"
2
3
4
5
6
- -(void)
handlerClickedButton:(void (^)(NSInteger btnIndex))aBlock; .
- -(void)
handlerClickedButton:(void (^)(NSInteger btnIndex))aBlock{ -
self.delegate = self; -
objc_setAssociatedObject(self, UIActionSheet_key_clicked, aBlock, OBJC_ASSOCIATION_COPY); - }
-
- -(void)
actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{ -
void (^block)(NSInteger btnIndex) = objc_getAssociatedObject(self, UIActionSheet_key_clicked); -
-
if (block) block(buttonIndex); - }
- @interface
UIAlertView (Block) -
- -(void)
handlerClickedButton:(void (^)(NSInteger btnIndex))aBlock; - -(void)
handlerCancel:(void (^)(void))aBlock; - -(void)
handlerWillPresent:(void (^)(void))aBlock; - -(void)
handlerDidPresent:(void (^)(void))aBlock; - -(void)
handlerWillDismiss:(void (^)(NSInteger btnIndex))aBlock; - -(void)
handlerDidDismiss:(void (^)(NSInteger btnIndex))aBlock; - -(void)
handlerShouldEnableFirst OtherButton:(BOOL (^)(void))aBlock; -
- @end
- UIAlertView
*alertView = [[[UIAlertView alloc] initWithTitle:@"title" message:@"msg" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil nil] autorelease]; - [alertView
handlerClickedButton:^(NSInteger btnIndex) { -
NSLogD(@"%d", btnIndex); - }];
- [alertView
show];