2014-08-31 51 views
0

試圖教會自己如何在OS X中自定義繪圖。我試圖在NView中嵌套NSTextView。Appkit/Quartz/CG在自定義視圖中正確嵌套NSTextView

Got top, want bottom

我似乎無法弄清楚我失蹤拿到NSTextView的行爲,如果它是沒有嵌入到其他自定義視圖步驟(即,文本應開始從左上角redering在提供給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) 

回答

1

您實際上並沒有在父視圖中嵌入text視圖。你可以用addSubview()來做到這一點。

let text = NSTextView(frame: textRect) 

    text.backgroundColor = grey 
    text.insertText(lipsum) 

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

是的,做到了。多麼簡單。邊幹邊學也有缺點;)。現在我甚至不需要給孩子畫圖。 – 2014-08-31 15:50:38

+0

邊學邊做,最難忘的學習方式! – chuckus 2014-08-31 15:54:56