Cocoa中是否有一个内置的,简单的输入框,用于检索字符串(就像我记得的那样在'Visual Basic中)?
我想我可以设计一个小窗口来做到这一点,但更喜欢使用原生的等价物(如果存在这样的东西;如果有的话我就找不到它).
谢谢.
Mar*_*rby 25
谢谢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 ""
}
}
Run Code Online (Sandbox Code Playgroud)
如果您想与文本字段的对话框,您可能需要自己创建它或者把一个NSTextField成NSAlert(注意,链接答案提出了一个模态对话框,将阻止所有交互与应用程序的其他部分;如果你不"我想要这样,你需要把它作为一张纸张呈现在窗口上).
更新 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)
}
Run Code Online (Sandbox Code Playgroud)
然后像这样调用它(我的应用程序的 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)
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4954 次 |
| 最近记录: |