我有一个自定义NSControl
,我正在尝试让函数edit(withFrame:editor:delegate:event:)
工作。调用它时,我希望字段编辑器出现在我的视图中,但没有任何反应。
我已经通读了该函数的文档,并创建了一个最小的示例:
class MyView: NSControl, NSControlTextEditingDelegate, NSTextDelegate {
required init?(coder: NSCoder) {
super.init(coder: coder)
isEnabled = true
}
override func mouseDown(with event: NSEvent) {
let editor = window!.fieldEditor(true, for: nil)!
let rect = bounds.insetBy(dx: 10.0, dy: 10.0)
self.edit(withFrame: rect, editor: editor, delegate: self, event: event)
}
func control(_ control: NSControl, textShouldBeginEditing fieldEditor: NSText) -> Bool {
return true
}
func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool {
self.endEditing(fieldEditor)
return true
}
func textShouldBeginEditing(_ textObject: NSText) -> Bool {
return true
}
}
从示例中可以看出,我不太确定是符合NSControlTextEditingDelegate
还是NSTextDelegate
。我实现的所有函数似乎都没有被调用。
还是我可能误解了该功能的目的?我应该覆盖它而不是调用它吗?
我不是现场编辑器的专家,但浏览Apple的文档似乎表明,它旨在在控件NSCell类上实现并自己呈现文本。如果希望字段编辑器显示在上面的示例中,则必须将字段编辑器插入到视图层次结构中。它不会自动发生。
class CustomTextControl: NSControl {
override func mouseDown(with event: NSEvent) {
// Make sure
if currentEditor() == nil {
if let controlWindow = window {
if controlWindow.makeFirstResponder(controlWindow) {
// It is safe to claim the field editor
if let editor = controlWindow.fieldEditor(true, for: nil) as? NSTextView {
addSubview(editor)
editor.frame = bounds
edit(withFrame: bounds, editor: editor, delegate: nil, event: event)
}
} else {
// Some other control has first responder, force first responder to resign
controlWindow.endEditing(for: nil)
}
}
}
}
}
我建议您阅读Apple关于Cocoa文本架构指南的文档。特别是使用字段编辑器和 NSCell 文档。这是一项不平凡的任务。
我想知道你想实现什么。