【问题标题】:editable nstextview from interface builder来自界面生成器的可编辑 nstextview
【发布时间】:2017-09-21 16:53:53
【问题描述】:

我无法编辑 nstextview。 这是我尝试的步骤。

  1. 从界面构建器中,我将“自定义视图”拖放到另一个视图中。 (我在那里找不到 nstextview。)
  2. 我将自定义视图表单“NSView”的类更改为“NSTextView”
  3. 接下来我运行我的项目,我可以看到正在渲染的文本视图(鼠标光标在文本视图区域的鼠标悬停时更改为文本模式)
  4. 但是,我无法插入/键入/编辑任何文本。

注意:我尝试过 setEditable、setSelectable 和设置其他帖子中推荐的 firstResponder 选项,但没有帮助。

【问题讨论】:

  • NSTextView 存在于 IB 中。它被称为“文本视图”。在搜索字段中输入“NSTextView”。
  • @willeke :是的,我看到了,但是在检查类名时,我发现它是一组视图,包括 nsscrollview、scroller、nsclipview 和 nstextview。那么,我们不能将 nstextview 作为独立的视图而不是其他视图吗?
  • 不,IB 中没有没有滚动视图的文本视图。也许 NSTextView 不应该在没有滚动视图的情况下使用。你不能使用换行文本字段吗?文本视图是弹出框还是拆分视图?
  • @Willeke,我正在使用带有滚动视图的视图,禁用垂直和水平滚动以向前移动。但是,当我尝试问题中的步骤时,仍然不确定为什么 NSTextView 作为独立的不起作用(或不应该起作用)。
  • 我认为这是因为当您以自定义视图方式执行操作时未设置 testStorage。在派生的 NSTextView 类中设置它可能是一种前进的方式。

标签: swift macos nstextview


【解决方案1】:

问题是当您按照描述的方式使用 Interface Builder 时,NSTextView 上的 textStorage 设置不正确。

我也想在 InterfaceBuilder 中使用不带 scrollView 的 NSTextView。在 Xcode 10 中,似乎不可能在某些自定义视图层次结构中放置一个单独的 NSTextView(早期的答案暗示这是可能的:https://stackoverflow.com/a/2398980/978300)。

可以使用问题中的“CustomView”方法来实现这一点 - 但是,这只会在属性检查器中具有简单的 NSView 属性(即,您将无法自定义字体等)。您可以通过在自定义类上使用 @IBInspectable 来传递一些详细信息。

连接检查器似乎工作正常。

示例 NSTextView 子类...

class MyTextView: NSTextView
{
    // init(frame: sets up a default textStorage we want to mimic in init(coder:
    init() {
        super.init(frame: NSRect.zero)
        configure()
    }

    /*
     It is not possible to set up a lone NSTextView in Interface Builder, however you can set it up
     as a CustomView if you are happy to have all your presentation properties initialised
     programatically. This initialises an NSTextView as it would be with the default init...
     */
    required init(coder: NSCoder) {
        super.init(coder: coder)!

        let textStorage = NSTextStorage()
        let layoutManager = NSLayoutManager()
        textStorage.addLayoutManager(layoutManager)

        // By default, NSTextContainers do not track the bounds of the NSTextview
        let textContainer = NSTextContainer(containerSize: CGSize.zero)
        textContainer.widthTracksTextView = true
        textContainer.heightTracksTextView = true

        layoutManager.addTextContainer(textContainer)
        replaceTextContainer(textContainer)

        configure()
    }

    private func configure()
    {
        // Customise your text here...
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-20
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-09
    相关资源
    最近更新 更多