[下载链接]https://git.oschina.net/ioszxh/iOS-UIAlertController
1.创建一个单列管理AlertController。
+ (AlertManage *)shareManager
{
static AlertManage *managerInstance = nil;
static dispatch_once_t token;
dispatch_once(&token, ^{
managerInstance = [[self alloc] init];
});
return managerInstance;
}
2.创建一个方法来初始化AlertController,这里用了一个OC中NS_REQUIRES_NIL_TERMINATION宏定义,其中UIAlertControllerStyle是AlertController的两种类型UIAlertControllerStyleActionSheet和UIAlertControllerStyleAlert。
- (AlertMananger *)creatAlertWithTitle:(NSString *)title message:(NSString *)message preferredStyle:(UIAlertControllerStyle)preferredStyle cancelTitle:(NSString *)canceTitle otherTitle:(NSString *)otherTitle,...NS_REQUIRES_NIL_TERMINATION{
self.alertCol = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:preferredStyle];
NSString *actionTitle = nil;
va_list args;//用于指向第一个参数
self.actionTitles = [NSMutableArray array];
[self.actionTitles addObject:canceTitle];
if (otherTitle) {
[self.actionTitles addObject:otherTitle];
va_start(args, otherTitle);//对args进行初始化,让它指向可变参数表里面的第一个参数
while ((actionTitle = va_arg(args, NSString*))) {
[self.actionTitles addObject:actionTitle];
}
va_end(args);
}
[self buildCancelAction];
[self buildOtherAction];
return [AlertMananger shareManager];
}
3.创建cancelAction
NSString *cancelTitle = self.actionTitles[0];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
self.indexBlock(0);
}];
[self.alertCol addAction:cancelAction];
4.创建其他按钮
- (void)buildOtherAction{
for (int i = 0 ; i < self.actionTitles.count; i++) {
if (i == 0)continue;
NSString *actionTitle = self.actionTitles[i];
UIAlertAction *action = [UIAlertAction actionWithTitle:actionTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
if (self.indexBlock) {
self.indexBlock(i);
}
}];
[self.alertCol addAction:action];
}
}
5.传入一个ViewController来展示AlertController,通过block来回调按钮的点击。
- (void)showWithViewController:(UIViewController *)viewController IndexBlock:(AlertIndexBlock)indexBlock{
if (indexBlock) {
self.indexBlock = indexBlock;
}
[viewController presentViewController:self.alertCol animated:NO completion:^{
}];
}
第一次写简书,有什么不对的地方请多多指正,谢谢支持!