jb0*_*007 25 iphone objective-c
我对目标C很新,我只想弄清楚我是否可以使用块或选择器作为UIAlertView的UIAlertViewDelegate参数 - 哪个更合适?
我尝试过以下但是它没有用,所以我不确定我是否在正确的轨道上?
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Checked In"
message:responseString
delegate:^(UIAlertView * alertView, NSInteger buttonIndex)
{
NSLog(@"Done!");
}
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
Run Code Online (Sandbox Code Playgroud)
谢谢!
dan*_*anh 28
很好的主意.这里是.就像警报视图一样,除了添加在解除警报时调用的块属性.(编辑 - 我从原始答案开始简化了这段代码.这是我现在在项目中使用的内容)
// 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
Run Code Online (Sandbox Code Playgroud)
您可以将此想法扩展为为其他委托方法提供块,但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];
Run Code Online (Sandbox Code Playgroud)