2015-09-30 50 views
4

我已經通過這裏和其他博客的許多線程,但無法解決這個問題。我在窗口的內容視圖中添加了一個子視圖。這裏是storyboard--如何爲NSView顯示陰影?

enter image description here -

我已經拖了出來customView出口到視圖控制器和這裏是視圖控制器的代碼 - 我在加入QuartzCore框架工作

import Cocoa 
import QuartzCore 

class ViewController: NSViewController { 

    @IBOutlet weak var customView: NSView! 
    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view. 
     self.view.wantsLayer = true 
     self.customView.wantsLayer = true 
     self.customView.layer?.backgroundColor = NSColor.redColor().CGColor 
     self.customView.layer?.cornerRadius = 5.0 
     self.customView.layer?.shadowOpacity = 1.0 
     self.customView.layer?.shadowColor = NSColor.blackColor().CGColor 
     self.customView.layer?.shadowOffset = NSMakeSize(0, -3) 
     self.customView.layer?.shadowRadius = 20 
    } 

    override var representedObject: AnyObject? { 
     didSet { 
     // Update the view, if already loaded. 
     } 
    } 
} 

我項目 - enter image description here

但陰影沒有出現,這裏是屏幕截圖 - enter image description here。我不能解決看似微不足道的問題。我錯過了什麼?謝謝你的幫助。

+0

也許你需要製作superview層支持。 –

+0

我已經爲窗口的內容視圖添加了self.view.wantsLayer = true。紅色視圖是內容視圖本身的子視圖。 – Abhishek

回答

7

如果我添加以下行它解決了problem-

 self.customView.shadow = NSShadow() 

最終代碼 -

import Cocoa 
import QuartzCore 

class ViewController: NSViewController { 

    @IBOutlet weak var customView: NSView! 
    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view. 
     self.view.wantsLayer = true 
     self.view.superview?.wantsLayer = true 
     self.customView.wantsLayer = true 
     self.customView.shadow = NSShadow() 
     self.customView.layer?.backgroundColor = NSColor.redColor().CGColor 
     self.customView.layer?.cornerRadius = 5.0 
     self.customView.layer?.shadowOpacity = 1.0 
     self.customView.layer?.shadowColor = NSColor.greenColor().CGColor 
     self.customView.layer?.shadowOffset = NSMakeSize(0, 0) 
     self.customView.layer?.shadowRadius = 20 
    } 

    override var representedObject: AnyObject? { 
     didSet { 
     // Update the view, if already loaded. 
     } 
    } 


} 

我不能識別的問題可能是這裏有人會指出來。

+2

NSShadow()是關鍵。接下來,託管視圖(例如超級視圖)需要wantsLayer爲true。 –

+0

在覈心動畫編程指南中,它指出一些圖層屬性不應該直接修改爲OS X中的圖層支持視圖。在這個屬性列表中是shadowOffset,shadowColor,shadowRadius和shadowOpacity。 https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreAnimation_guide/CreatingBasicAnimations/CreatingBasicAnimations.html因此,最好創建一個陰影對象,在這個對象上設置屬性,然後將其分配給圖層的陰影。 – RookiePro