---
title: "IOS之UIAlertView的事件处理（免Delegate）"
author: "ikrboy"
date: "2014-01-12T12:28:39Z"
tags: []
categories: ["移动开发"]
slug: "ios-uialertview-delegate"
draft: false
lastmod: "2014-01-12T13:27:16Z"
id: 2002976
url: "https://ikrboy.iteye.com/blog/2002976"
---

利用这种方式可以避免继承Delegate，不然有很多UIAlertview的时候，处理起来就麻烦了。有效地达到了代码分层的好处。

1.添加头文件，文件请见附件。具体用法可以参照：[https://github.com/jivadevoe/UIAlertView-Blocks](https://github.com/jivadevoe/UIAlertView-Blocks "https://github.com/jivadevoe/UIAlertView-Blocks")

```
#include "RIButtonItem.h"
#include "UIAlertView+Blocks.h"
```

 2.实现代码，下面的方法是一个UIButton触发的点击事件的自定义方法

```
//弹出警告框，并实现警告框按钮的触发事件
- (IBAction)showAlert:(UIButton *)sender forEvent:(UIEvent *)event {
    
    RIButtonItem *cancelItem = [RIButtonItem item];
    cancelItem.label = @"No";
    cancelItem.action = ^
    {
        //为NO时的处理
        NSLog(@"为NO时的处理");
    };
    
    RIButtonItem *confirmItem = [RIButtonItem item];
    confirmItem.label = @"Yes";
    confirmItem.action = ^
    {
        //为YES时的处理
        NSLog(@"为YES时的处理");
    };
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Delete This Item?"
                                                                                message:@"Are you sure you want to delete this really important thing?"
                                                                       cancelButtonItem:cancelItem
                                                                       otherButtonItems:confirmItem, nil];
    [alert show];

}
```

   
![](http://dl2.iteye.com/upload/attachment/0093/0688/f0aa19cd-1118-38f1-9d3f-18ef31baa164.png)