使NSTextField接受返回并输入不结束编辑
问题描述:
我目前正在用swift编写文本编辑器,并且在按Enter/Return时插入新行(“\ n”)时遇到问题。使NSTextField接受返回并输入不结束编辑
现在,当按下回车键时,textField会插入一个新行,但无任何理由结束编辑。
这里是我的功能,它只会在按下回车键时被调用。
@IBAction func textFieldAction(_ sender: NSTextField) {
self.textField?.stringValue.append("\n")
self.textField?.selectAll(nil)
}
如果有更多的我的代码所需要的全部文件可以在这里找到: https://github.com/notalent/manuscript-mac/blob/master/Manuscript/Document.swift
答
我认为正确的答案是“不使用NSTextField
;使用NSTextView”。 NSTextField
不是为了做你想做的事而设计的。 Cocoa Text Architecture Guide在NSTextField
和NSTextView
上都有大量信息。另见this question here on SO。
但是,如果您坚持使用NSTextField
,则可以实施代理方法control:textView:doCommandBySelector:
,以便在NSTextField
中提供对返回/输入密钥(尤其是其他内容)的特殊处理。请参阅Apple's Technical Q&A QA1454, "How to make NSTextField accept tab, return and enter keys"。
说真的,虽然......只是使用NSTextView
。 :)
为什么不使用'TextView'来代替? –
因为据我所知,您不能为NSTextView设置(归属)占位符 – IliasMay