swift - 如何在 NSTextView 周围绘制边框

标签 swift macos cocoa 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 又名 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);

最佳答案

另一种选择是为 TextView 创建一个单独的类并使用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()
}
}

关于swift - 如何在 NSTextView 周围绘制边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61003786/

相关文章:

arrays - 如何修复循环遍历数组中索引的代码?

inheritance - 协议(protocol)类型对象的 Swift 数组

xcode - 使用相机和表格单元 SWIFT

swift - macOS中如何阻止其他应用程序监听鼠标事件?

macos - 将关键字文件通过管道传送到 grep 中

ios - 如何在成功登录 UIWebView 后重定向回应用程序

mysql - 将数据从旧的 mysql 安装迁移到 Mac 中的新安装

objective-c - 在 Objective-C 应用程序之间传递参数

iphone - 显示禁用位置服务的用户位置

multithreading - Cocoa 应用程序中无法解释的 NSUndoManager 崩溃/断言