NSSegmentedControl置于模糊视图时显示异常问题
我之前也踩过这个坑!在macOS的Popover里放NSSegmentedControl时出现的奇怪方形背景,大多是控件样式和Popover视图层级的适配问题,给你几个亲测有效的解决思路:
调整NSSegmentedControl的样式设置
先检查控件的segmentStyle属性,默认样式可能和Popover的半透明背景不兼容。试试把它设置为.plain:segmentedControl.segmentStyle = .plain如果是在Interface Builder里开发,直接在属性面板找到「Segment Style」选项切换成Plain即可。另外,也可以尝试禁用控件的默认背景绘制:
segmentedControl.wantsLayer = true segmentedControl.layer?.backgroundColor = NSColor.clear.cgColor优化Popover内容视图的背景
Popover的默认content view可能带有不透明的背景层,导致控件显示异常。你可以把content view的背景设为透明:if let contentView = popover.contentViewController?.view { contentView.wantsLayer = true contentView.layer?.backgroundColor = NSColor.clear.cgColor }要是用IB开发,直接选中content view,在属性面板把「Background」改成Clear Color就行。
用NSVisualEffectView作为容器
既然Popover本身是半透明的视觉效果控件,把NSSegmentedControl放在NSVisualEffectView里,能更好地适配系统外观。你可以在IB里给content view嵌套一个NSVisualEffectView,或者代码创建:let effectView = NSVisualEffectView() effectView.blendingMode = .behindWindow effectView.material = .popover // 把segmentedControl加到effectView里,再将effectView设为popover的contentView popover.contentViewController?.view = effectView检查系统版本适配
如果你是在Big Sur及以后的系统上开发,新的系统外观可能和旧的控件样式冲突。可以临时在Info.plist里添加NSRequiresAquaSystemAppearance并设为YES,强制使用传统Aqua外观验证是否解决问题——不过这只是临时排查方案,建议最终还是适配新系统的视觉规范。
内容的提问来源于stack exchange,提问作者Supertecnoboff

