NSAlert组件应用总结
一、引言
在桌面软件开发中,当用户进行非法的操作或有风险的操作时,时长需要弹出警告框来提示用户。在OS X系统上,NSAlert是专门的警告框组件。其提供了简洁的接口供开发者进行使用。
二、NSAlert的简单使用
使用警告框最简单的使用方式是提示错误信息,错误信息警告只起到提示用户的作用,其只有一个OK按钮,点击后警告框会关闭。示例如下:
1 2 3 4 5
| - (IBAction)alert:(id)sender { NSError * error = [NSError errorWithDomain:@"testError" code:1001 userInfo:@{@"userid":@"1000"}]; NSAlert * alert = [NSAlert alertWithError:error]; [alert runModal]; }
|
效果图如下:
警告框的展现有两种方式,分别为模态窗与弹出抽屉。弹出抽屉会显示在当前绑定的窗口上,模态窗则会自成窗口,弹出在屏幕中央。
你也可以对警告框进行自定义设置,例如文本,标题,图标等,示例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| - (IBAction)alert:(id)sender { NSAlert * alert = [[NSAlert alloc]init]; alert.icon = [NSImage imageNamed:@"icon"]; alert.messageText = @"警告信息"; alert.informativeText = @"额外提供的内容"; alert.showsHelp = YES; alert.helpAnchor = @"mac"; alert.alertStyle = NSAlertStyleInformational; alert.showsSuppressionButton = YES; [alert.suppressionButton setTarget:self]; [alert.suppressionButton setAction:@selector(click)]; [alert addButtonWithTitle:@"1"]; [alert addButtonWithTitle:@"2"]; [alert addButtonWithTitle:@"3"]; [alert addButtonWithTitle:@"4"]; long res = [alert runModal]; NSLog(@"%ld",res); }
|
效果如下:
三、NSAlert属性与方法解析
NSAlert类中的属性和方法解析如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| + (NSAlert *)alertWithError:(NSError *)error;
@property (copy) NSString *messageText;
@property (copy) NSString *informativeText;
@property (null_resettable, strong) NSImage *icon;
- (NSButton *)addButtonWithTitle:(NSString *)title;
@property (readonly, copy) NSArray<NSButton *> *buttons;
@property BOOL showsHelp;
@property (nullable, copy) NSString *helpAnchor;
@property NSAlertStyle alertStyle;
@property BOOL showsSuppressionButton NS_AVAILABLE_MAC(10_5);
@property (nullable, readonly, strong) NSButton *suppressionButton NS_AVAILABLE_MAC(10_5);
@property (nullable, weak) id<NSAlertDelegate> delegate;
- (NSModalResponse)runModal;
- (void)beginSheetModalForWindow:(NSWindow *)sheetWindow completionHandler:(void (^ __nullable)(NSModalResponse returnCode))handler NS_AVAILABLE_MAC(10_9);
|
NSAlertDelegate协议中只定义了一个方法,如下:
1 2 3 4 5
| @protocol NSAlertDelegate <NSObject> @optional
- (BOOL)alertShowHelp:(NSAlert *)alert; @end
|
除了上面列出的方法外,NSAlert中还有两个已经弃用的便捷构造和弹出方法,如下:
1 2 3 4
| + (NSAlert *)alertWithMessageText:(nullable NSString *)message defaultButton:(nullable NSString *)defaultButton alternateButton:(nullable NSString *)alternateButton otherButton:(nullable NSString *)otherButton informativeTextWithFormat:(NSString *)format, ...;
- (void)beginSheetModalForWindow:(NSWindow *)window modalDelegate:(nullable id)delegate didEndSelector:(nullable SEL)didEndSelector contextInfo:(nullable void *)contextInfo;
|