[下載鏈接]https://git.oschina.net/ioszxh/iOS-UIAlertController
1.創(chuàng)建一個單列管理AlertController宋渔。
+ (AlertManage *)shareManager
{
static AlertManage *managerInstance = nil;
static dispatch_once_t token;
dispatch_once(&token, ^{
managerInstance = [[self alloc] init];
});
return managerInstance;
}
2.創(chuàng)建一個方法來初始化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.創(chuàng)建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.創(chuàng)建其他按鈕
- (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:^{
}];
}
第一次寫簡書倦逐,有什么不對的地方請多多指正唬涧,謝謝支持疫赎!