Cocoa Appkit/Quartz/CG在自定义视图中正确嵌套NSTextView

Cocoa Appkit/Quartz/CG在自定义视图中正确嵌套NSTextView,cocoa,swift,quartz-graphics,appkit,drawing2d,Cocoa,Swift,Quartz Graphics,Appkit,Drawing2d,尝试自学如何在OS X中进行自定义绘图。我正在尝试在NSView中嵌套NSTextView 我似乎无法找出我缺少的步骤,以使NSTextView表现得好像它没有嵌入到另一个自定义视图中一样(即,文本应该在提供给NSTextView的框架中从左上角开始重新显示,从左到右,从上到下) 实际上,您没有将文本视图嵌入父视图中。您可以使用addSubview()实现这一点 let text=NSTextView(帧:textRect) text.backgroundColor=灰色 text.inser

尝试自学如何在OS X中进行自定义绘图。我正在尝试在NSView中嵌套NSTextView

我似乎无法找出我缺少的步骤,以使
NSTextView
表现得好像它没有嵌入到另一个自定义视图中一样(即,文本应该在提供给
NSTextView
的框架中从左上角开始重新显示,从左到右,从上到下)


实际上,您没有将
文本
视图嵌入父视图中。您可以使用
addSubview()
实现这一点

let text=NSTextView(帧:textRect)
text.backgroundColor=灰色
text.insertText(lipsum)

self.addSubview(text)//是的。多简单啊。在实践中学习确实有其缺点;)。现在我甚至不必给孩子打电话了。
import Cocoa
import AppKit
import XCPlayground

class MyView : NSView {
    let lipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

    override init(frame: NSRect) {
        super.init(frame:frame)
        self.wantsLayer = true
    }

    required init(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func drawRect(dirtyRect: NSRect) {
        super.drawRect(dirtyRect)

        let grey = NSColor.grayColor()
        self.layer?.backgroundColor = grey.CGColor

        let boundaryRect = NSInsetRect(dirtyRect, 10, 10)
        let textRect = NSInsetRect(boundaryRect, 10, 10)

        let path = NSBezierPath(roundedRect: boundaryRect, xRadius: 5, yRadius: 5)
        path.stroke()


        let text = NSTextView(frame: textRect)

        text.backgroundColor = grey
        text.insertText(lipsum)

        text.drawRect(textRect)
    }
}

var frame = NSRect(x: 0, y: 0, width: 400, height: 400)

let myView = MyView(frame: frame)

let textView = NSTextView(frame:frame)
textView.insertText(myView.lipsum)

XCPShowView("my view", myView)
XCPShowView("text view", textView)
    let text = NSTextView(frame: textRect)

    text.backgroundColor = grey
    text.insertText(lipsum)

    self.addSubview(text) // <---------
}