我是objective C的新手,我只是想弄清楚是否可以使用块或选择器作为UIAlertView的UIAlertViewDelegate参数--哪一个更合适?
我已经尝试了以下方法,但就是不起作用,所以我不确定我是否在正确的轨道上?
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Checked In"
message:responseString
delegate:^(UIAlertView * alertView, NSInteger buttonIndex)
{
NSLog(@"Done!");
}
cancelButtonTitle:@"OK"
otherButtonTitles: nil];谢谢!
发布于 2012-04-10 10:52:40
好主意。这就是了。就像警告视图一样,except添加了一个block属性,该属性在警告解除时被调用。(编辑-从原始答案开始,我已经简化了这段代码。以下是我现在在项目中使用的内容)
// 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是最常见的。
这样叫它:
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];发布于 2015-11-17 14:33:21
正如苹果公司的文档所说,人们必须使用UIAlertController来实现这种方法
UIAlertController对象向用户显示一条警告消息。此类取代了用于显示警报的UIActionSheet和UIAlertView类。在使用所需的操作和样式配置警报控制器之后,使用presentViewController:animated:completion:方法呈现它。
除了向用户显示消息之外,您还可以将操作与警报控制器相关联,以便为用户提供一种响应方式。对于您使用addAction:方法添加的每个操作,警报控制器都会使用操作详细信息配置一个按钮。当用户点击该操作时,警报控制器将执行您在创建操作对象时提供的块。Apple Docs.
UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"My Alert"
message:@"This is an alert."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];发布于 2012-04-11 00:53:00
在github上查看这个UIAlertView-Blocks类别。我使用这个,它工作得很好。
https://stackoverflow.com/questions/10082383
复制相似问题