【问题标题】:How to display shadow for NSView?如何为 NSView 显示阴影?
【发布时间】:2015-12-27 20:34:15
【问题描述】:

我在这里和其他博客浏览了很多线程,但无法解决这个问题。我在窗口的内容视图中添加了一个子视图。这是故事板--

-

我已将 customView 的出口拖出到视图控制器,这是视图控制器的代码 -

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.
        }
    }
}

我在我的项目中添加了 QuartzCore 框架 -

但是阴影没有出现,这是屏幕截图 - .

我无法解决看似微不足道的问题。我错过了什么?感谢您的帮助。

【问题讨论】:

  • 可能你也需要让 superview layer-backed。
  • 我已经为窗口的内容视图添加了 self.view.wantsLayer = true 。红色视图是内容视图本身的子视图。

标签: macos swift cocoa calayer nsview


【解决方案1】:

如果我添加以下行它可以解决问题-

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.
        }
    }


}

我无法确定问题可能是这里有人会指出它。

【讨论】:

  • NSShadow() 是关键。接下来,托管视图(例如 superview)需要将 wantLayer 设置为 true。
  • 在核心动画编程指南中,它说不应该直接修改 OS X 中的图层支持视图的某些图层属性。在这个属性列表中是 shadowOffset、shadowColor、shadowRadius、shadowOpacity。 developer.apple.com/library/content/documentation/Cocoa/…所以最好创建一个阴影对象,在这个对象上设置属性,然后分配给图层的阴影。
  • 在我的例子中,NSShadow 使图层cornerRadius 无效
  • 这对我有帮助!我只需要将 WantLayer 设置为 true
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多