阻止UIAlertViewDelegate [英] Block for UIAlertViewDelegate

查看:114
本文介绍了阻止UIAlertViewDelegate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对目标C很新,我只想弄清楚我是否可以使用块或选择器作为UIAlertView的UIAlertViewDelegate参数 - 哪个更合适?

I'm pretty new to objective C and I'm just trying to figure out if I can use a block or a selector as the UIAlertViewDelegate argument for UIAlertView - and which is more appropriate?

我已经尝试过以下但是它没有用,所以我不确定我是否在正确的轨道上?

I've tried the following but it just isn't working so I'm not sure if I'm on the right track or not?

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Checked In" 
    message:responseString
    delegate:^(UIAlertView * alertView, NSInteger buttonIndex)
                                                    {
                                                       NSLog(@"Done!");
                                                   } 
    cancelButtonTitle:@"OK" 
    otherButtonTitles: nil];

谢谢!

推荐答案

好主意。这里是。就像警报视图一样,除了添加在解除警报时调用的块属性。 (编辑 - 我从原始答案开始简化了这段代码。以下是我现在在项目中使用的内容)

Great idea. Here it is. Just like alert view, except adds a block property that's invoked when the alert is dismissed. (Edit - I've simplified this code since the original answer. Here's what I use now in projects)

//  AlertView.h
//

#import <UIKit/UIKit.h>

@interface AlertView : UIAlertView

@property (copy, nonatomic) void (^completion)(BOOL, NSInteger);

- (id)initWithTitle:(NSString *)title message:(NSString *)message cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSArray *)otherButtonTitles;

@end

//
//  AlertView.m

#import "AlertView.h"

@interface AlertView () <UIAlertViewDelegate>

@end

@implementation AlertView

- (id)initWithTitle:(NSString *)title message:(NSString *)message cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSArray *)otherButtonTitles {

    self = [self initWithTitle:title message:message delegate:self cancelButtonTitle:cancelButtonTitle otherButtonTitles:nil];

    if (self) {
        for (NSString *buttonTitle in otherButtonTitles) {
            [self addButtonWithTitle:buttonTitle];
        }
    }
    return self;
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {

    if (self.completion) {
        self.completion(buttonIndex==self.cancelButtonIndex, buttonIndex);
        self.completion = nil;
    }
}

@end

你可以扩展这个想法为其他委托方法提供块,但didDismiss是最常见的。

You can extend this idea to supply blocks for other delegate methods, but the didDismiss is the most common.

这样称呼:

AlertView *alert = [[AlertView alloc] initWithTitle:@"Really Delete" message:@"Do you really want to delete everything?" cancelButtonTitle:@"Nevermind" otherButtonTitles:@[@"Yes"]];

alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
    if (!cancelled) {
        [self deleteEverything];
    }
};
[alert show];

这篇关于阻止UIAlertViewDelegate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆