You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 4中如何通过纯代码实现NSOutlineView的Source List高亮样式?

在Swift 4中纯代码配置NSOutlineView的Source List高亮样式

嘿,我之前刚好折腾过纯代码实现Source List样式的NSOutlineView,其实和你在Storyboard里点一下"Source List"选项的效果完全一致,咱们一步步来搞定:

1. 初始化NSOutlineView并设置核心样式

这一步是关键,直接对应Storyboard里的"Source List"配置:

// 先定义好你需要的frame,比如侧边栏的区域
let outlineFrame = CGRect(x: 0, y: 0, width: 200, height: view.frame.height)
let outlineView = NSOutlineView(frame: outlineFrame)

// 开启Source List样式
outlineView.style = .sourceList
// 设置选中时的高亮风格为Source List专属样式
outlineView.selectionHighlightStyle = .sourceList

// 别忘了设置代理和数据源
outlineView.delegate = self
outlineView.dataSource = self

2. 配置承载它的NSScrollView

Source List通常放在滚动视图里,为了匹配系统侧边栏的外观,咱们需要调整滚动视图的样式:

let scrollFrame = outlineFrame // 和outlineView的frame保持一致
let scrollView = NSScrollView(frame: scrollFrame)
scrollView.documentView = outlineView

// 开启垂直滚动,自动隐藏滚动条
scrollView.hasVerticalScroller = true
scrollView.autohidesScrollers = true

// 去掉边框,设置系统控件背景色,和Source List风格统一
scrollView.borderType = .noBorder
scrollView.backgroundColor = NSColor.controlBackgroundColor

// 把滚动视图添加到你的父视图里
view.addSubview(scrollView)

3. 数据源补充(可选但推荐)

如果你的OutlineView有分组项,记得在数据源里标记出来,Source List会自动给分组项应用对应的样式(比如灰色背景、加粗文字):

extension YourViewController: NSOutlineViewDataSource {
    func outlineView(_ outlineView: NSOutlineView, isGroupItem item: Any) -> Bool {
        // 根据你的数据模型判断是否为分组项,比如:
        // return item is CategoryGroupModel
        return false // 替换成你的实际逻辑
    }
    
    // 其他数据源方法(比如outlineView(_:child:ofItem:)等)这里就不赘述了
}

这样配置完,你的NSOutlineView就会拥有和Storyboard里设置"Source List"完全一样的高亮和外观风格啦。如果还需要自定义细节,比如调整选中颜色,也可以通过outlineView.selectionColor来设置,但默认的系统样式已经很贴合macOS的设计规范了。

内容的提问来源于stack exchange,提问作者Johannes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:35:28