GUNAlert 是 UIAlertView 和 UIAlertController 的简单封装。对于需要保持与 iOS 版本 < 8 兼容的应用,它被设计为大多数常用场景的简单即插即用解决方案。
要运行示例项目,请克隆仓库,并首先从示例目录运行 pod install
。
在使用警告之前,您需要实例化 GUNAlert
类并确保其引用在处理警告之前不会消失。以下是一个示例
在您的 UIViewController
中创建一个 GUNAlert
类的实例,并将其分配为 strong
属性。
@interface MyViewController ()
@property (strong, nonatomic) GUNAlert *alert;
@end
@implementation GUNViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.alert = [[GUNAlert alloc] initWithViewController: self];
}
@end
在大多数情况下,您想要通知用户一个事实并对其进行确认或做出决定。为此,GUNAlert
提供了两个辅助方法
要创建 '取消' 警告或称只有一个操作的警告,请使用以下方法
[self.alert cancelAlertWithTitle:@"Success!"
message:@"You've just won a lottery."
cancelTitle:@"Yay!"
cancelHandler:^{
[self transferLargeSumOfMoney];
}];
要创建 '取消 & 确定' 警告或称有两个操作的警告,请使用以下方法
[self.alert cancelOkAlertWithTitle:@"Your meal is ready!"
message:@"Do you want something to drink?"
cancelTitle:@"Not really"
cancelHandler:^{
[self prepareOrder];
}
okTitle:@"Sure I do"
okHandler:^{
[self addDrinkToOrder];
[self prepareOrder];
}];
首先准备一个包含每个操作标题的数组。
NSArray *titles = @[
@"Yes",
@"No",
@"Maybe"
];
然后准备一个包含每个操作处理程序的数组。这两个数组必须具有相同数量的元素。
NSArray *handlers = @[
^{
[self makeACall]
},
^{
},
^{
if (arc4random_uniform(2)) {
[self makeACall]
};
},
];
最后,使用这两个数组在以下方法中
[self.alert alertWithTitle:@"Hey I've just met you"
message:@"Call me"
titles:titles
handlers:handlers];
在 iOS 7.1 和 iOS 8 上进行测试
将 GUNAlert.h 和 GUNAlert.m 复制到您的项目并按需修改。
Michał Taszycki,[email protected]
GUNAlert 可在 MIT 协议下获得。有关更多信息,请参阅 LICENSE 文件。