2.1 NSAlert
NSAlert是Cocoa中用来进行警告或提醒类的窗口,其类似于JOptionalPane或MessageBox。常用的有两种类型,一种是仅以信息提示,另一种是信息提示辅以事件响应,请看下文介绍。
2.1.1
1.仅信息提示类
private func showAlert(){
let alert = NSAlert()
alert.addButton(withTitle: "OK")
alert.messageText = "Test Alert"
alert.informativeText = "This is a concrete information for user."
alert.alertStyle = .informational
alert.icon = NSImage(named: "close")
alert.runModal()
}
说明:调用NSAlert类我们只需封装一个方法就可以。NSAlert的属性有标题、详细文本信息、按钮文本、样式和显示图片。其中显示图片是非必须的,如果没有设置系统会默认提供一个默认图片;按钮文本最多可添加三个。
2.信息提示辅以事件响应
private func showAlert(){
let alert = NSAlert()
alert.addButton(withTitle: "OK")
alert.messageText = "Test Alert"
alert.informativeText = "This is a concrete information for user."
alert.alertStyle = .informational
alert.icon = NSImage(named: "close")
alert.beginSheetModal(for: self.view.window!) { (returnCode) in
switch returnCode.rawValue{
case 1000:
print("------> 1000")
case 1001:
print("------> 1000")
case 1002:
print("------> 1000")
default:
break
}
}
}
说明:在beginSheetMoal()中采用闭包将返回码进行回调。1000、1001与1002分别对应生成的三个按钮(本例为了方便仅设置一个Button)的点击回调选项。需要注意的是,仅信息提示的NSAlert弹窗是可以在其弹出后自由移动的,而信息提示辅以事件响应则是NSAlert弹窗顶部与window顶部平齐不可移动的,文末有截图可发现。
运行截图:
信息提示
信息提示辅以事件响应