0

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

得到了顶部,想要底部

我似乎无法弄清楚我缺少的步骤,以NSTextView使其表现得好像它没有嵌入另一个自定义视图中(即,文本应该从提供给的框架的左上角开始重新渲染NSTextView,从左到- 右和从上到下)。

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)
4

1 回答 1

1

您实际上并没有将text视图嵌入到父视图中。你可以用addSubview().

    let text = NSTextView(frame: textRect)

    text.backgroundColor = grey
    text.insertText(lipsum)

    self.addSubview(text) // <---------
}
于 2014-08-31T15:44:52.880 回答