Cocoa中是否有一个内置的,简单的输入框,用于检索字符串(就像我记得的那样,有很好的Visual Basic?)
我想我可以设计一个小窗口来做到这一点但更喜欢使用原生的等价物(如果存在这样的东西;如果有的话,我找不到它。)
感谢。
答案 0 :(得分:23)
感谢DarkDust指出我正确的方向。我永远不会在NSAlerts中搜索“附件视图”(我没有正确的条款来欺骗Google或SO给我货物!)。我也忘了提到我正在使用Swift,所以我已经敲了一个快速翻译:
func getString(title: String, question: String, defaultValue: String) -> String {
let msg = NSAlert()
msg.addButtonWithTitle("OK") // 1st button
msg.addButtonWithTitle("Cancel") // 2nd button
msg.messageText = title
msg.informativeText = question
let txt = NSTextField(frame: NSRect(x: 0, y: 0, width: 200, height: 24))
txt.stringValue = defaultValue
msg.accessoryView = txt
let response: NSModalResponse = msg.runModal()
if (response == NSAlertFirstButtonReturn) {
return txt.stringValue
} else {
return ""
}
}
答案 1 :(得分:5)
如果您想要一个带有文本字段的对话框,您需要自己创建或put an NSTextField
into an NSAlert
(请注意,链接的答案会显示一个模态对话框,会阻止所有互动与你的应用程序的其余部分;如果你不想这样,你需要present it as a sheet on a window)。
答案 2 :(得分:2)
为Swift 5更新。我总是将可重复使用的项目(如警报)放在应用管理器类中。而且我喜欢将闭包保留为一种类型别名,以更好地组织它们并保持论点更清晰。
typealias promptResponseClosure = (_ strResponse:String, _ bResponse:Bool) -> Void
func promptForReply(_ strMsg:String, _ strInformative:String, vc:ViewController, completion:promptResponseClosure) {
let alert: NSAlert = NSAlert()
alert.addButton(withTitle: "OK") // 1st button
alert.addButton(withTitle: "Cancel") // 2nd button
alert.messageText = strMsg
alert.informativeText = strInformative
let txt = NSTextField(frame: NSRect(x: 0, y: 0, width: 200, height: 24))
txt.stringValue = ""
alert.accessoryView = txt
let response: NSApplication.ModalResponse = alert.runModal()
var bResponse = false
if (response == NSApplication.ModalResponse.alertFirstButtonReturn) {
bResponse = true
}
completion(txt.stringValue, bResponse)
}
然后这样称呼(我的应用程序的git管理部分需要它):
myAppManager.promptForReply("Changes were added to the repo, do you want to commit them?", "If you are commiting, add your commit message below.", vc: self, completion: {(strCommitMsg:String, bResponse:Bool) in
if bResponse {
print(strCommitMsg)
}
})