這不會使它阻塞,但我已經寫了一個子類來添加塊風格的語法,這使得它更容易處理buttonClickedAtIndex方法,而無需做一個委託和一大堆if語句,如果你有多個UIAlertViews在一個類中。
#import <UIKit/UIKit.h>
@interface UIAlertViewBlock : UIAlertView<UIAlertViewDelegate>
- (id) initWithTitle:(NSString *)title message:(NSString *)message block: (void (^)(NSInteger buttonIndex))block
cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... NS_AVAILABLE(10_6, 4_0);
@end
#import "UIAlertViewBlock.h"
@interface UIAlertViewBlock()
{
void (^_block)(NSInteger);
}
@end
@implementation UIAlertViewBlock
- (id) initWithTitle:(NSString *)title message:(NSString *)message block: (void (^)(NSInteger buttonIndex))block
cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... NS_AVAILABLE(10_6, 4_0)
{
if (self = [super initWithTitle:title message:message delegate:self cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles, nil])
{
_block = block;
}
return self;
}
- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
_block(buttonIndex);
}
@end
然後在這裏調用它是一些示例代碼。另一個很酷的部分是因爲一個塊關閉了局部變量,所以我可以訪問當我顯示UIAlertView時存在的所有狀態。使用傳統的委託方法,您必須將所有臨時狀態存儲到類級別變量中,才能在委託中調用buttonClickedAtIndex時訪問它。這非常乾淨。
{
NSString *value = @"some random value";
UIAlertViewBlock *b = [[UIAlertViewBlock alloc] initWithTitle:@"Title" message:@"Message" block:^(NSInteger buttonIndex)
{
if (buttonIndex == 0)
NSLog(@"%@", [value stringByAppendingString: @" Cancel pressed"]);
else if (buttonIndex == 1)
NSLog(@"Other pressed");
else
NSLog(@"Something else pressed");
}
cancelButtonTitle:@"Cancel" otherButtonTitles:@"Other", nil];
[b show];
}
謝謝。我重新設計了我的功能邏輯。 – kesrut 2010-09-21 15:27:53