【问题标题】:Appkit / Quartz / CG Nesting NSTextView within a custom view correctlyAppkit / Quartz / CG 在自定义视图中正确嵌套 NSTextView
【发布时间】:2014-10-24 22:59:24
【问题描述】:

试图自学如何在 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)

【问题讨论】:

    标签: cocoa swift quartz-graphics appkit drawing2d


    【解决方案1】:

    您实际上并未将text 视图嵌入到父视图中。你可以通过addSubview() 做到这一点。

        let text = NSTextView(frame: textRect)
    
        text.backgroundColor = grey
        text.insertText(lipsum)
    
        self.addSubview(text) // <---------
    }
    

    【讨论】:

    • 是的,做到了。多么简单。边做边学确实有它的缺点;)。现在我什至不必对孩子调用 draw 了。
    猜你喜欢
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    • 2017-09-23
    • 1970-01-01
    相关资源
    最近更新 更多