Several UIAlertViews for a delegate

做~自己de王妃 提交于 2019-11-28 17:47:59

Tag the UIAlertViews like this:

#define kAlertViewOne 1
#define kAlertViewTwo 2

UIAlertView *alertView1 = [[UIAlertView alloc] init...
alertView1.tag = kAlertViewOne;

UIAlertView *alertView2 = [[UIAlertView alloc] init...
alertView2.tag = kAlertViewTwo;

and then differentiate between them in the delegate methods using these tags:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if(alertView.tag == kAlertViewOne) {
        // ...
    } else if(alertView.tag == kAlertViewTwo) {
        // ...
    }
}
Dan J

FYI, if you want to target just iOS 4 users (which is reasonable now that ~98.5% of clients have at least iOS 4 installed), you should be able to use Blocks to do really nice inline handling of UIAlertViews.

Here's a Stackoverflow question explaining it:
Block for UIAlertViewDelegate

I tried using Zachary Waldowski's BlocksKit framework for this. His UIAlertView(BlocksKit) API reference looked really good. However, I tried to follow his instructions to import the BlocksKit framework into my project, but unfortunately I couldn't get it to work.

So, as Can Berk Güder suggests, I've used UIAlertView tags for now. But at some point in future I'm going to try to move to using Blocks (preferably one which supports ARC out of the box)!

easier & newer

UIAlertView *alert = [[UIAlertView alloc] init...
alert.tag = 1;

UIAlertView *alert = [[UIAlertView alloc] init...
alert.tag = 2;



- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if(alertView.tag == 1) {
        // first alert...
    } else  {
        // sec alert...
    }
}

all done!

You can overcome this whole ordeal and prevent yourself from using tags by enhancing UIAlertView to use block callbacks. Check out this blog post I wrote on the subject.

I've always thought using tags is a bit of a hack. If you do use them, at least set some defined constants for the tag numbers.

Instead, I use properties like this:

In the interface section:

@property (nonatomic, weak) UIAlertView *overDueAlertView;
@property (nonatomic, weak) UIAlertView *retryPromptAlertView;

Creating the alert view:

UIAlertView *alert = [[UIAlertView alloc] init...
self.overDueAlertView = alert;
[alert show];

Delegate method:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
  if (alertView == self.overDueAlertView) {
    // Overdue alert
  } else if (alertView == self.retryPromptAlertView) {
    // Retry alert
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!