【问题标题】:Custom NSView with NSStackView使用 NSStackView 自定义 NSView
【发布时间】:2020-03-28 16:15:06
【问题描述】:

我正在尝试使用始终相同的自定义视图来实现 NSStackView。所以我已经定义了我的 xib 文件,链接了我的类中的所有内容,关联了类,......但我确信我错过了一些东西,因为视图中的内容没有出现。非常感谢您的帮助。

我的故事板:

我的xib文件:

我运行以下代码时的结果:

我的文件是这样的:

class CustomView: NSView, NSTableViewDelegate, NSTableViewDataSource {
    @IBOutlet weak var segmentControlOutlet: NSSegmentedControl!
    @IBOutlet weak var tableViewOutlet: NSTableView!
}

class ViewController: NSViewController, NSStackViewDelegate {
    
    @IBOutlet weak var stackViewOutlet: NSStackView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        stackViewOutlet.delegate = self
        
        let newView = CustomView()
        stackViewOutlet.addArrangedSubview(newView)
        
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }


}

【问题讨论】:

  • 尝试向堆栈视图添加一些约束。我在这里进行了快速测试,没有约束,堆栈缩小到零高度和零宽度,所以它是不可见的。您还可以在尝试调试视图问题时为背景添加颜色。
  • 感谢您的回复,堆栈视图被限制在窗口的边界,所以理论上它应该出现。但事实上,当我要求 newView 的合适尺寸时,我的高度和宽度都是 0.0 ...

标签: swift xcode macos nsview nsstackview


【解决方案1】:

我找到了答案,您需要正确启动视图。这样做:

class CustomView: NSView, NSTableViewDelegate, NSTableViewDataSource {

    @IBOutlet var viewOutlet: NSView!
    @IBOutlet weak var segmentControlOutlet: NSSegmentedControl!
    @IBOutlet weak var tableViewOutlet: NSTableView!

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        Bundle.main.loadNibNamed("CustomView", owner: self, topLevelObjects: nil)
        addSubview(viewOutlet)
        viewOutlet.frame = self.bounds
        viewOutlet.autoresizingMask = [.height, .width]
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        Bundle.main.loadNibNamed("CustomView", owner: self, topLevelObjects: nil)
        addSubview(viewOutlet)
        viewOutlet.frame = self.bounds
        viewOutlet.autoresizingMask = [.height, .width]
    }

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        // Drawing code here.
    }
}

请注意,当您加载 nib 名称时,“CustomView”是您的 xib 文件的名称;)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    • 2017-06-27
    • 2011-11-15
    • 2015-03-09
    • 1970-01-01
    • 2010-12-25
    相关资源
    最近更新 更多