首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用NSControl的编辑(withFrame:editor:delegate:event:)?

如何使用NSControl的编辑(withFrame:editor:delegate:event:)?
EN

Stack Overflow用户
提问于 2019-01-27 21:26:41
回答 1查看 183关注 0票数 1

我有一个自定义的NSControl,并且我正在尝试让函数edit(withFrame:editor:delegate:event:)工作。在调用它时,我希望字段编辑器出现在我的视图中,但什么也没有发生。

我已经通读了该函数的文档,并且创建了一个最小的示例:

代码语言:javascript
复制
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。我实现的函数似乎都没有被调用。

或者我可能误解了函数的目的?我应该重写它而不是调用它吗?

EN

回答 1

Stack Overflow用户

发布于 2019-02-12 07:18:05

我不是字段编辑器方面的专家,但浏览苹果公司的文档似乎表明,它被设计为在控件NSCell类上实现并自己呈现文本。如果希望字段编辑器出现在上面的示例中,则必须将字段编辑器插入到视图层次结构中。这不是自动发生的。

代码语言:javascript
复制
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 EditorNSCell文档。这不是一项微不足道的任务。

我想知道你想要达到什么目的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54388621

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档