我对 objective-c 还是很陌生,我只是想弄清楚是否可以将块或选择器用作UIAlertView的UIAlertViewDelegate参数-哪个更合适?
我已经尝试了以下方法,但是它无法正常工作,所以我不确定是否在正确的轨道上?
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Checked In"
message:responseString
delegate:^(UIAlertView * alertView, NSInteger buttonIndex)
{
NSLog(@"Done!");
}
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
谢谢!
最佳答案
好点子。这里是。就像警报 View 一样,区别在于添加了一个块属性,该属性在警报被消除时被调用。 (编辑-自原始答案以来,我已简化了此代码。这是我现在在项目中使用的代码)
// 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
您可以将此思想扩展到为其他委托(delegate)方法提供块,但didDismiss是最常见的。
这样称呼它:
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];
关于iphone - 阻止UIAlertViewDelegate,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10082383/