2015-09-30 46 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