2014-09-06 99 views
2

如何讓我的NSStackView一個接一個地展示我的視野?我的藍色方框在我的紅色方框上繪製。Swift NSStackView:通過做。我究竟做錯了什麼?

import Cocoa 

class TestView : NSView{ 
    override init() { 
    super.init(frame: NSRect(x: 0,y: 0,width: 100,height: 100)) 
    } 

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

    override func drawRect(dirtyRect: NSRect) { 
    super.drawRect(dirtyRect) 
    NSColor.redColor().setFill() 
    NSBezierPath.fillRect(self.bounds) 
    } 
} 

class TestView2 : NSView{ 
    override init() { 
    super.init(frame: NSRect(x: 0,y: 0,width: 100,height: 100)) 
    } 

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

    override func drawRect(dirtyRect: NSRect) { 
    super.drawRect(dirtyRect) 
    NSColor.blueColor().setFill() 
    NSBezierPath.fillRect(self.bounds) 
    } 
} 

class AppDelegate: NSObject, NSApplicationDelegate { 

    @IBOutlet weak var window: NSWindow! 

    @IBOutlet weak var searchFacetItems: SearchFacetSelectorView! 
    @IBOutlet weak var searchFacetHeader: SearchFacetSelectorHeader! 
    var content : NSStackView! 
    let testView = TestView() 
    let testView2 = TestView2() 

    func applicationDidFinishLaunching(aNotification: NSNotification?) { 
    // Insert code here to initialize your application 
    content = NSStackView(frame: window.contentView.bounds) 
     content.orientation = NSUserInterfaceLayoutOrientation.Vertical 
     content.alignment = NSLayoutAttribute.CenterX 

    content.addView(testView, inGravity: NSStackViewGravity.Center) 
    content.addView(testView2, inGravity: NSStackViewGravity.Center) 


    window.contentView = content! 
    } 

    func applicationWillTerminate(aNotification: NSNotification?) { 
    // Insert code here to tear down your application 
    } 


} 

通過閱讀

這不是AppKit的學習,但也許我會得到一些線索:HOW TO USE UIVIEWS WITH AUTO LAYOUT PROGRAMMATICALLY

Auto Layout Guide

回答

0

您應該能夠通過調整NSRect做到這一點座標。目前,您已經有了兩個NSRects使用完全相同的座標:如果你想NSView水平(右側),毗鄰其他的

NSRect(x: 0, y: 0, width: 100, height: 100) 

NSRect(0, 0, 100, 100) // TestView1 
NSRect(100, 0, 100, 100) // TestView2 

垂直下方:

NSRect(0, 0, 100, 100) // TestView1 
NSRect(0, -100, 100, 100) // TestView2 
+0

我曾嘗試過,它確實有效。但我期待堆棧視圖能夠合理地佈置它管理的視圖。 – 2014-09-07 10:25:30

0

視圖沒有任何描述其首選大小的約束,例如intrinsicContentSize或顯式約束。而NSStackView只增加了相對於彼此放置其堆疊視圖的限制,而不是限制個別視圖的大小。

如果沒有它們,它們在疊加軸上的尺寸變得模糊不清,並且通常會將所有尺寸設置爲單個視圖。在你的例子中,我猜想藍色框不是在紅色框的頂部繪製,而是紅色框的高度爲0(並且在藍色視圖之後堆疊)。

NSButton添加到堆棧視圖不存在此問題,因爲它們具有已定義的intrinsicContentSize

根據您的觀點是什麼 - 他們有內在大小,或將它們通過限制內部子視圖定義 - 你要麼要重寫intrinsicContentSize或添加那些最終定義它們的高度限制。


編輯:哦,確保translatesAutoresizingMaskIntoConstraints設置爲false你要添加到堆棧觀點的看法(它看起來並不像你從樣品代碼)。如果不是這樣,你會很快陷入麻煩,因爲自動調整約束條件試圖定位視圖並與堆棧視圖添加的約束衝突。