我很难为文本文件显示设置NSScrollView。
定义了一个适当大小的窗口:
......
let contentRect = NSMakeRect(0.0, 0.0, 800, 600)
let styleMask:NSWindow.StyleMask = [.titled, .closable, .miniaturizable, .resizable]
let window = NSWindow(contentRect:contentRect, styleMask:styleMask, backing:.buffered, defer:true)
window.minSize = NSMakeSize(800.0, 600.0)
window.isReleasedWhenClosed = false
window.tabbingMode = .disallowed
window.makeKeyAndOrderFront(nil)
window.center() // Wait until after makeKeyAndOrderFront so the window sizes properly first
window.title = NSLocalizedString("GCode File", comment:"GCode File window")
......
设置滚动视图并将其放入窗口,然后设置窗口约束:
......
let scrollView = NSScrollView(frame: (window.contentView?.frame)!)
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.borderType = .noBorder
scrollView.backgroundColor = NSColor.gray
scrollView.hasVerticalScroller = true
window.contentView?.addSubview(scrollView)
window.contentView?.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollView]|", options: [], metrics: nil, views: ["scrollView": scrollView]))
window.contentView?.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[scrollView]|", options: [], metrics: nil, views: ["scrollView": scrollView]))
......
设置clipview并将clipview设置为scrollview的内容视图,然后配置scrollview和clipview的约束:
......
let clipView = NSClipView()
clipView.translatesAutoresizingMaskIntoConstraints = false
scrollView.contentView = clipView
scrollView.addConstraint(NSLayoutConstraint(item: clipView, attribute: .left, relatedBy: .equal, toItem: scrollView, attribute: .left, multiplier: 1.0, constant: 0))
scrollView.addConstraint(NSLayoutConstraint(item: clipView, attribute: .top, relatedBy: .equal, toItem: scrollView, attribute: .top, multiplier: 1.0, constant: 0))
scrollView.addConstraint(NSLayoutConstraint(item: clipView, attribute: .right, relatedBy: .equal, toItem: scrollView, attribute: .right, multiplier: 1.0, constant: 0))
scrollView.addConstraint(NSLayoutConstraint(item: clipView, attribute: .bottom, relatedBy: .equal, toItem: scrollView, attribute: .bottom, multiplier: 1.0, constant: 0))
......
设置nstextview并将文件内容加载到nstextview:
......
var textView: NSTextView!
var textStorage: NSTextStorage!
textStorage = NSTextStorage()
let layoutManager = NSLayoutManager()
textStorage.addLayoutManager(layoutManager)
let textContainer = NSTextContainer(containerSize: window.contentView!.bounds.size)
layoutManager.addTextContainer(textContainer)
textView = NSTextView(frame: window.contentView!.bounds, textContainer: textContainer)
textView.isEditable = true
textView.isSelectable = true
textView.textStorage?.append(file)
scrollView.documentView = textView
......
然后我运行该应用程序,将窗口和内容呈现为:
怎么了?我看不到从文件加载的全文(被截断),也没有垂直滚动条显示。我相信约束配置中缺少一些东西。
如果有经验,请提出建议!