2015-02-06 25 views
2

我知道我可以如何以編程方式執行此操作。我知道在爲iOS創建故事板時非常簡單,就在屬性檢查器中。然而,當爲OSX創建故事板時,我沒有看到它對於我的任何視圖控制器或其在Xcode 6.1.1中的視圖。如何使用OSX使用情節提要時創建NSView的背景

如何更改視圖的背景而無需創建視圖控制器關聯用它。我的應用程序有很多簡單的視圖,但背景會從一個視圖變爲另一個視圖。

回答

6

你不應該需要一個新的viewController來改變一個NSView的背景。如果你沒有子類的NSView,那麼你可以直接電話諮詢:

myView.wantsLayer = true 
myView.layer!.backgroundColor = CGColorGetConstantColor(kCGColorBlack) 

我不知道,如果你能嚴格故事板做到這一點,雖然你可以使用用戶可能設置wantsLayer = true在故事板定義的運行時屬性。

enter image description here

+1

謝謝,這有助於。我改爲使用NSView代替並使用以下代碼:https://github.com/benzguo/demosthenes/blob/master/demosthenes/Categories/NSView.swift – Alex 2015-02-06 21:56:38

1

可以在故事板改變NSView的背景顏色,如果你繼承NSView和子類分配給您的觀點:

enter image description here

enter image description here

使用這個子類實施:

import Cocoa 

class ViewWithBackgroundColor : NSView { 
    @IBInspectable var backgroundColor: NSColor? { 
     get { 
      guard let layer = layer, backgroundColor = layer.backgroundColor else { return nil } 
      return NSColor(CGColor: backgroundColor) 
     } 

     set { 
      wantsLayer = true 
      layer?.backgroundColor = newValue?.CGColor 
     } 
    } 

    override init(frame frameRect: NSRect) { 
     super.init(frame: frameRect) 
    } 

    required init?(coder: NSCoder) { 
     super.init(coder: coder) 
    } 
} 

背景顏色在設計時不顯示,但在運行時顯示。

也許有人知道如何在設計時更新視圖(最好不要重寫繪製方法)。

3

這是另一種達到同樣效果的方法。

在您的NSView下添加NSBox並調整NSBox的框架與NSView一樣。

更改標題的位置無,箱式給定製,邊框類型,以

這是截圖:

enter image description here

而不是增加您的NSView,NSButton,的NSTextField或者作爲NSBox的子視圖。

這是結果:

enter image description here