如何在 NSTextView 周围绘制边框

How to draw border around NSTextView

我只是想在 NSTextView 周围画一个黑色边框,运行 遇到了麻烦。下面的代码是 NSTextView 的子类:

override init(frame: NSRect, textContainer: NSTextContainer?)
{
    super.init(frame:frame, textContainer: textContainer)

    self.wantsLayer = true
    self.layer?.borderColor = NSColor.black.cgColor
    self.layer?.borderWidth = 1.0
    self.layer?.cornerRadius = 0.0
}

self.wantsLayer = true 代码导致 NSTextView 消失。还有其他方法可以实现吗?

编辑:这就是我将 NSTextView aka PageView 添加到其父项 view:

的方式
    let textContainer = NSTextContainer()
    textContainer.widthTracksTextView = true
    textContainer.heightTracksTextView = true

    let pageView = PageView(frame: CGRect(x: 0, y: pagesViewOriginY, width: self.paperSize.width, height: self.paperSize.height), textContainer: textContainer)
    self.addSubview(pageView);

    self.layoutManager.addTextContainer(textContainer);

是否可以使用滚动视图并像这样设置边框:

scrollView.borderType = .lineBorder

或者,您可以将文本视图嵌入到 NSView 中并在其周围绘制边框:

let embedderRect = NSMakeRect(10, 590, _wndW - 20, 252)
let embedderView = NSView(frame:embedderRect)
let textStorage = NSTextStorage()
let layoutManager = NSLayoutManager()
textStorage.addLayoutManager(layoutManager)
let textContainer = NSTextContainer()
layoutManager.addTextContainer(textContainer)
let textView = NSTextView(frame:NSMakeRect( 1, 1, embedderRect.size.width - 2, embedderRect.size.height - 2 ), textContainer: textContainer)
embedderView.wantsLayer = true
embedderView.layer?.borderColor = NSColor.black.cgColor
embedderView.layer?.borderWidth = 1.0
embedderView.layer?.cornerRadius = 0.0
embedderView.addSubview (textView)
window.contentView!.addSubview (embedderView)

另一种方法是为文本视图创建一个单独的 class 并使用 draw() 提供框架:

class TextView: NSTextView {
override func draw(_ rect: NSRect) {
  super.draw(rect)
  let border:NSBezierPath = NSBezierPath(rect: bounds)
  let borderColor = NSColor.black
  borderColor.set()
  border.lineWidth = 2.0
  border.stroke()
}
}