gpt4 book ai didi

iphone - 阻止 UIAlertViewDelegate

转载 作者:太空狗 更新时间:2023-10-30 03:11:13 28 4
gpt4 key购买 nike

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

我已经尝试了以下方法,但它不起作用,所以我不确定我是否在正确的轨道上?

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

谢谢!

最佳答案

好主意。这里是。就像警报 View 一样,只是添加了一个 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

您可以扩展这个想法,为其他委托(delegate)方法提供 block ,但最常见的是 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com