開一組新的檔案 UIViewController+Alert.h
、UIViewController+Alert.m
分別放以下內容:
#import <UIKit/UIKit.h>
@interface UIViewController (Alert)
- (void)presentAlertWithTitle:(NSString *)title
message:(NSString *)message;
@end
#import "UIViewController+Alert.h"
@implementation UIViewController (Alert)
- (void)presentAlertWithTitle:(NSString *)title
message:(NSString *)message
{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title
message:message
preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:@"OK"
style:UIAlertActionStyleCancel
handler:nil]];
[self presentViewController:alertController
animated:YES
completion:nil];
}
@end
在別的 ViewController 就可以用以下方法呼叫:
#import "UIViewController+Alert.h"
@implementation MyViewController
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self presentAlertWithTitle:@"Oops!"
message:@"This app is about to crash!"];
}
@end
如果很常用的話可以考慮在 precompiled prefix header 裡面 import UIViewController+Alert.h
。
可以吃 callback 的宣告範例
Objective-C
Swift
使用方法
Objective-C
使用方法:
Swift