Mac开发基础25-NSAlert

NSAlert 是 macOS 应用中的一个重要控件,用于显示警告与通知对话框。NSAlert 允许开发者创建和配置弹出窗口,用于通知用户、确认操作或显示错误信息。

基本使用

创建和显示简单的警告框

Objective-C

#import <Cocoa/Cocoa.h>

// 实例化 NSAlert
NSAlert *alert = [[NSAlert alloc] init];

// 设置警告标题
[alert setMessageText:@"警告"];

// 设置详细信息
[alert setInformativeText:@"这是一个警告对话框"];

// 添加按钮
[alert addButtonWithTitle:@"确定"];
[alert addButtonWithTitle:@"取消"];

// 显示同步模式对话框 (阻塞,等待用户响应)
NSModalResponse response = [alert runModal];
if (response == NSAlertFirstButtonReturn) {
    NSLog(@"用户点击了确定");
} else if (response == NSAlertSecondButtonReturn) {
    NSLog(@"用户点击了取消");
}

Swift

import Cocoa

// 实例化 NSAlert
let alert = NSAlert()

// 设置警告标题
alert.messageText = "警告"

// 设置详细信息
alert.informativeText = "这是一个警告对话框"

// 添加按钮
alert.addButton(withTitle: "确定")
alert.addButton(withTitle: "取消")

// 显示同步模式对话框 (阻塞,等待用户响应)
let response = alert.runModal()
if response == .alertFirstButtonReturn {
    print("用户点击了确定")
} else if response == .alertSecondButtonReturn {
    print("用户点击了取消")
}

配置警告类型和样式

Objective-C

// 设置警告类型 (例如:NSAlertStyleWarning,NSAlertStyleInformational,NSAlertStyleCritical)
[alert setAlertStyle:NSAlertStyleWarning];

Swift

// 设置警告类型 (例如:.warning,.informational,.critical)
alert.alertStyle = .warning

显示异步模式对话框

Objective-C

// 显示异步模式对话框,使用 completionHandler 来处理用户响应
[alert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) {
    if (returnCode == NSAlertFirstButtonReturn) {
        NSLog(@"用户点击了确定");
    } else if (returnCode == NSAlertSecondButtonReturn) {
        NSLog(@"用户点击了取消");
    }
}];

Swift

// 显示异步模式对话框,使用 completionHandler 来处理用户响应
alert.beginSheetModal(for: self.window!) { response in
    if response == .alertFirstButtonReturn {
        print("用户点击了确定")
    } else if response == .alertSecondButtonReturn {
        print("用户点击了取消")
    }
}

高级用法

为警告对话框添加自定义视图

Objective-C

// 创建一个自定义视图 (例如,包含一个 NSTextField)
NSTextField *textField = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 200, 24)];
[textField setStringValue:@"请输入你的名字"];

// 添加自定义视图到警告对话框
[alert setAccessoryView:textField];

Swift

// 创建一个自定义视图 (例如,包含一个 NSTextField)
let textField = NSTextField(frame: NSRect(x: 0, y: 0, width: 200, height: 24))
textField.stringValue = "请输入你的名字"

// 添加自定义视图到警告对话框
alert.accessoryView = textField

禁用按钮的自动布局

默认情况下,NSAlert 会为按钮设置自动布局。对于更复杂的布局,可以禁用自动布局。

Objective-C

// 禁用按钮的自动布局
[alert setShowsSuppressionButton:YES];
[alert.suppressionButton setTitle:@"不再显示此消息"];

Swift

// 禁用按钮的自动布局
alert.showsSuppressionButton = true
alert.suppressionButton?.title = "不再显示此消息"

响应抑制按钮点击

NSAlert 可以包含一个抑制按钮(Suppression Button),用于抑制将来的显示。

Objective-C

// 在 completionHandler 中处理抑制按钮点击
[alert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) {
    if ([alert suppressionButton].state == NSControlStateValueOn) {
        NSLog(@"用户选择不再显示此消息");
    }
}];

Swift

// 在 completionHandler 中处理抑制按钮点击
alert.beginSheetModal(for: self.window!) { response in
    if alert.suppressionButton?.state == .on {
        print("用户选择不再显示此消息")
    }
}

创建不同样式的警告对话框

Objective-C

// 设置对话框为信息提示样式
[alert setAlertStyle:NSAlertStyleInformational];

// 设置对话框为警告样式
[alert setAlertStyle:NSAlertStyleWarning];

// 设置对话框为严重错误样式
[alert setAlertStyle:NSAlertStyleCritical];

Swift

// 设置对话框为信息提示样式
alert.alertStyle = .informational

// 设置对话框为警告样式
alert.alertStyle = .warning

// 设置对话框为严重错误样式
alert.alertStyle = .critical

封装工具类

为了更方便地使用 NSAlert,可以封装一个工具类,提供常见功能的高层接口。

Objective-C

#import <Cocoa/Cocoa.h>

@interface NSAlertHelper : NSObject

+ (void)showAlertWithTitle:(NSString *)title message:(NSString *)message inWindow:(NSWindow *)window;
+ (void)showCustomAlertWithTitle:(NSString *)title message:(NSString *)message accessoryView:(NSView *)accessoryView inWindow:(NSWindow *)window;
+ (void)showAsyncAlertWithTitle:(NSString *)title message:(NSString *)message inWindow:(NSWindow *)window completionHandler:(void (^)(NSModalResponse))completionHandler;

@end

@implementation NSAlertHelper

+ (void)showAlertWithTitle:(NSString *)title message:(NSString *)message inWindow:(NSWindow *)window {
    NSAlert *alert = [[NSAlert alloc] init];
    [alert setMessageText:title];
    [alert setInformativeText:message];
    [alert addButtonWithTitle:@"确定"];
    [alert addButtonWithTitle:@"取消"];
    [alert beginSheetModalForWindow:window completionHandler:nil];
}

+ (void)showCustomAlertWithTitle:(NSString *)title message:(NSString *)message accessoryView:(NSView *)accessoryView inWindow:(NSWindow *)window {
    NSAlert *alert = [[NSAlert alloc] init];
    [alert setMessageText:title];
    [alert setInformativeText:message];
    [alert addButtonWithTitle:@"确定"];
    [alert addButtonWithTitle:@"取消"];
    [alert setAccessoryView:accessoryView];
    [alert beginSheetModalForWindow:window completionHandler:nil];
}

+ (void)showAsyncAlertWithTitle:(NSString *)title message:(NSString *)message inWindow:(NSWindow *)window completionHandler:(void (^)(NSModalResponse))completionHandler {
    NSAlert *alert = [[NSAlert alloc] init];
    [alert setMessageText:title];
    [alert setInformativeText:message];
    [alert addButtonWithTitle:@"确定"];
    [alert addButtonWithTitle:@"取消"];
    [alert beginSheetModalForWindow:window completionHandler:completionHandler];
}

@end

Swift

import Cocoa

class NSAlertHelper {
    
    // 显示简单的警告对话框
    static func showAlert(title: String, message: String, inWindow window: NSWindow) {
        let alert = NSAlert()
        alert.messageText = title
        alert.informativeText = message
        alert.addButton(withTitle: "确定")
        alert.addButton(withTitle: "取消")
        alert.beginSheetModal(for: window, completionHandler: nil)
    }
    
    // 显示带有自定义视图的警告对话框
    static func showCustomAlert(title: String, message: String, accessoryView: NSView, inWindow window: NSWindow) {
        let alert = NSAlert()
        alert.messageText = title
        alert.informativeText = message
        alert.accessoryView = accessoryView
        alert.addButton(withTitle: "确定")
        alert.addButton(withTitle: "取消")
        alert.beginSheetModal(for: window, completionHandler: nil)
    }
    
    // 显示异步警告对话框
    static func showAsyncAlert(title: String, message: String, inWindow window: NSWindow, completionHandler: @escaping (NSApplication.ModalResponse) -> Void) {
        let alert = NSAlert()
        alert.messageText = title
        alert.informativeText = message
        alert.addButton(withTitle: "确定")
        alert.addButton(withTitle: "取消")
        alert.beginSheetModal(for: window, completionHandler: completionHandler)
    }
}

使用示例

Objective-C

// 使用示例:显示简单的警告对话框
[NSAlertHelper showAlertWithTitle:@"警告" message:@"这是一个警告对话框" inWindow:self.window];

// 使用示例:显示带有自定义视图的警告对话框
NSTextField *textField = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 200, 24)];
[textField setStringValue:@"请输入你的名字"];
[NSAlertHelper showCustomAlertWithTitle:@"输入" message:@"请输入信息" accessoryView:textField inWindow:self.window];

// 使用示例:显示异步警告对话框
[NSAlertHelper showAsyncAlertWithTitle:@"异步警告" message:@"这是一个异步警告对话框" inWindow:self.window completionHandler:^(NSModalResponse returnCode) {
    if (returnCode == NSAlertFirstButtonReturn) {
        NSLog(@"用户点击了确定");
    } else if (returnCode == NSAlertSecondButtonReturn) {
        NSLog(@"用户点击了取消");
    }
}];

Swift

// 使用示例:显示简单的警告对话框
NSAlertHelper.showAlert(title: "警告", message: "这是一个警告对话框", inWindow: self.window!)

// 使用示例:显示带有自定义视图的警告对话框
let textField = NSTextField(frame: NSRect(x: 0, y: 0, width: 200, height: 24))
textField.stringValue = "请输入你的名字"
NSAlertHelper.showCustomAlert(title: "输入", message: "请输入信息", accessoryView: textField, inWindow: self.window!)

// 使用示例:显示异步警告对话框
NSAlertHelper.showAsyncAlert(title: "异步警告", message: "这是一个异步警告对话框", inWindow: self.window!) { response in
    if response == .alertFirstButtonReturn {
        print("用户点击了确定")
    } else if response == .alertSecondButtonReturn {
        print("用户点击了取消")
    }
}

总结

通过了解 NSAlert 的基本使用、配置警告类型和样式、显示异步模式对话框、添加自定义视图、响应抑制按钮点击以及创建不同样式的警告对话框等高级用法,并封装工具类,你将能够更高效地使用 NSAlert 创建复杂的提示系统。在实际应用中,合理使用这些技巧可以显著提升用户界面的灵活性和用户体验。

posted @ 2024-08-06 18:16  Mr.陳  阅读(26)  评论(0编辑  收藏  举报