macOS桌面开发NSAlert的使用
1 简述
附加到窗口的模式对话框或工作表,可以定义标题,描述详情,图标,按钮等。
@interface NSAlert : NSObject
NSAlert
总体分为两类:
-
显示在应用程序中的提示框
- (void)beginSheetModalForWindow:(NSWindow *)sheetWindow completionHandler:(void (^ _Nullable)(NSModalResponse returnCode))handler API_AVAILABLE(macos(10.9));
-
单个警报,应用程序外的提示框
[alert runModal];
2 常用属性
@property (copy) NSString *messageText; // 主要提示信息
@property (copy) NSString *informativeText;// 其他提示信息
@property (null_resettable, strong) NSImage *icon; // 自定义图标,不设置会使用系统默认图标 NSApplicationIcon
/*!
typedef NS_ENUM(NSUInteger, NSAlertStyle) {
NSAlertStyleWarning = 0,
NSAlertStyleInformational = 1,
NSAlertStyleCritical = 2
};
*/
@property NSAlertStyle alertStyle;
@property BOOL showsHelp; // 是否显示帮助锚点
@property (nullable, copy) NSHelpAnchorName helpAnchor; // 锚点内容
@property BOOL showsSuppressionButton API_AVAILABLE(macos(10.5)); // 是否显示复选框
@property (nullable, readonly, strong) NSButton *suppressionButton API_AVAILABLE(macos(10.5));
@property (nullable, strong) NSView *accessoryView API_AVAILABLE(macos(10.5)); // 附件信息
3 初始化
NSAlert *alert = [[NSAlert alloc] init];
4 示例
NSAlert *alert = [[NSAlert alloc] init];
alert.icon = [NSImage imageNamed:@"apple-touch-icon-next"];
alert.alertStyle = NSAlertStyleWarning;
[alert addButtonWithTitle:@"确定"];
[alert addButtonWithTitle:@"取消"];
alert.messageText = @"title";
alert.informativeText = @"msg";
alert.showsSuppressionButton = YES;
// 方式1
[alert beginSheetModalForWindow:self.view.window completionHandler:^(NSModalResponse returnCode) {
if (returnCode == NSAlertFirstButtonReturn) {
NSLog(@"确定");
} else if (returnCode == NSAlertSecondButtonReturn) {
NSLog(@"取消");
} else {
NSLog(@"else");
}
}];
/*! 方式2
NSModalResponse response = [alert runModal];
if (response == NSModalResponseStop) {
}
if (response == NSModalResponseAbort) {
}
if (response == NSModalResponseContinue) {
}
*/
5 !!!提醒!!!
使用方式1的时候需要注意的是window不能为nil,不要讲NSAlert
添加在HomeVC的ViewDidLoad中,此时Window还没创建成功。
网友评论