我有一个自定义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
。我实现的所有功能都似乎被调用。
还是我也许误解了功能的目的是什么?我应该代替覆盖它调用呢?
我在字段编辑器专家,但浏览苹果的文件似乎表明,它被设计为在控制的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)
}
}
}
}
}
我建议你在苹果的Cocoa文字架构指南文档阅读起来。具体地说Working with the Field Editor和NSCell文档。这是一个不平凡的任务。
什么是你想实现我不知道。