【问题标题】:How to add an NSHostingView in Interface Builder如何在 Interface Builder 中添加 NSHostingView
【发布时间】:2021-12-18 22:39:05
【问题描述】:

我有一个像这样的简单 NSHostingView:

class HostedCircleView: NSHostingView<Circle> {}

我想将此HostedCircleView 包含在情节提要视图中。

所以我向我的故事板添加了一个自定义视图,并使用一些布局约束对其进行定位。然后我使用身份检查器将它的类更改为HostedCircleView

但是 IB 使用 init?(coder aDecoder: NSCoder) 初始化器,默认情况下没有实现。所以我添加了以下实现:

required init?(coder aDecoder: NSCoder) {
    super.init(rootView: Circle())
}

这样做的问题是它完全忽略了编码器,并且在我运行它时它没有将所需的约束从 IB 添加到我的视图中。相反,它会记录以下错误:

Failed to set (contentViewController) user defined inspected property on (NSWindow): Unable to install constraint on view.  Does the constraint reference something from outside the subtree of the view?  That's illegal. constraint:<NSLayoutConstraint:0x60000351a5d0 NSView:0x7f8596416530.bottom == sbapp.Special:0x7f8598023000.bottom   (active)> view:<NSView: 0x7f8596416530>

如何解决?

【问题讨论】:

    标签: xcode macos swiftui interface-builder appkit


    【解决方案1】:

    我们不能那样使用它,但我们可以将它用作内容 - 即。我们可以使用聚合而不是继承(在 SwiftUI 的情况下实际上和往常一样)。

    这是一个可能的方法的演示

    class HostedCircleView: NSView {  // << use this in Storyboard !!
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
    
            let content = NSHostingView(rootView: Circle())
            content.translatesAutoresizingMaskIntoConstraints = false
    
            self.addSubview(content)
            content.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
            content.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
            content.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
            content.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      • 1970-01-01
      • 2013-01-23
      • 2014-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多