我有一个自定义的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。我实现的函数似乎都没有被调用。
或者我可能误解了函数的目的?我应该重写它而不是调用它吗?
发布于 2019-02-12 07:18:05
我不是字段编辑器方面的专家,但浏览苹果公司的文档似乎表明,它被设计为在控件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文档。这不是一项微不足道的任务。
我想知道你想要达到什么目的。
https://stackoverflow.com/questions/54388621
复制相似问题