我有一个自定义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
。我实现的功能似乎都没有被调用。
还是我可能误解了该功能的目的?我应该覆盖它而不是调用它吗?
答案 0 :(得分:0)
我不是字段编辑器的专家,但是浏览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)
}
}
}
}
}
我建议您阅读有关Cocoa Text Architecture Guide的Apple文档。特别是Working with the Field Editor和NSCell文档。这是一项艰巨的任务。
你想达到什么目的?