跳过正文
  1. Posts/

为 NSView 增加 backgroundColor

·1 分钟·

NSView 作为 Cocoa 中最基本的构成元素,是构成整个 Mac App 视图体系的基础,和 UIView 在 iOS 世界中的位置一样重要,可是在 UIView 里司空见惯的背景色设置,在 NSView 中却不见身影。

在 iOS 中,设置 UIView 的背景色很简单。


import UIKit

let frame = CGRect(origin: .zero, size: CGSize(width: 100, height: 100))
let view = UIView(frame: frame)

view.backgroundColor = .blue

而在 macOS 上,使用 NSView 背景色需要如下设置:


import Cocoa

let frame = CGRect(origin: .zero, size: CGSize(width: 100, height: 100))
let view = NSView(frame: frame)

view.wantsLayer = true
view.layer?.backgroundColor = NSColor.blue.cgColor

UIView 自身有一个 backgroundColor 的属性,而在 NSView 中是没有的,你需要做的是设置 View 所包含的 layer 的背景色。而且 layer 是 Optional 的,也就意味着 NSView 默认是不包含 layer 的,所以你还需要设置 wantsLayer 为 true 让 NSView 创建 layer 出来。

在 Apple 的官方文档 有针对 wantsLayer 的一些说明

Setting the value of this property to true turns the view into a layer-backed view—that is, the view uses a CALayer object to manage its rendered content. Creating a layer-backed view implicitly causes the entire view hierarchy under that view to become layer-backed. Thus, the view and all of its subviews (including subviews of subviews) become layer-backed. The default value of this property is false.

相关文章

Apple Event Sandboxing

·2 分钟
问题背景 # 最近在修改某个 Mac 应用,其原理就是通过执行一段 AppleScript 获取 OmniFocus 的信息,然后进行可视化展示,但是总取不到数据。

RxSwift 中的几种 Subject

·3 分钟
文中所用插图均出自书籍 《RxSwift - Reactive Programming with Swift》 Subject 在 Rx 的世界里是这么一种存在,其既可以作为观测者,也可以作为被观测者。自然而然想到的是 Subject 本身就可以作为一种过渡桥接信号的手段,它订阅某个信号,一旦信号收到序列,转头它就又把信号散发给自己的观测者了。