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

macOS SwiftUI开发:NSCursor中缺失系统调整大小光标如何解决?

解决macOS SwiftUI中获取系统调整大小光标问题

你提到的系统常用调整尺寸光标,可通过以下两种方式获取:

1. 使用NSCursor公开预设实例

NSCursor原生提供了覆盖常见边缘、角落场景的调整光标:

  • 上下边缘调整:NSCursor.resizeUpDown(你代码中已使用)
  • 左右边缘调整:NSCursor.resizeLeftRight
  • 左上角/右下角对角线调整:NSCursor.resizeUpLeftDownRight
  • 右上角/左下角对角线调整:NSCursor.resizeUpRightDownLeft

这些光标完全匹配系统自带样式,无需额外资源。

2. 加载系统光标资源自定义(针对特殊需求)

若预设实例无法满足需求,可直接加载系统内置光标图片创建自定义NSCursor:

// 示例:加载系统左右调整光标
if let cursorImage = NSImage(named: NSImage.Name("resizeLeftRightCursor")) {
    let customCursor = NSCursor(image: cursorImage, hotSpot: NSPoint(x: cursorImage.size.width/2, y: cursorImage.size.height/2))
    customCursor.push()
}

系统光标资源命名规律直观,比如上下调整对应resizeUpDownCursor,四角调整分别对应resizeUpLeftDownRightCursor、resizeUpRightDownLeftCursor。

优化后的代码示例

以左右边缘调整场景为例,修改后的代码如下:

struct ContentView: View {
    
    @AppStorage("InspectorWidth") var inspectorWidth = 200.0
    
    var body: some View {
        ZStack(alignment: .leading) {
            Color.cyan
                .frame(width: CGFloat(inspectorWidth))
            
            Divider()
                .padding(.horizontal, 2)
                .onHover { inside in
                    if inside {
                        NSCursor.resizeLeftRight.push()
                    } else {
                        NSCursor.pop()
                    }
                }
                .gesture(
                    DragGesture()
                        .onChanged { drag in
                            inspectorWidth = max(100, inspectorWidth + Double(drag.translation.width))
                        }
                )
        }
        .frame(width: 600, alignment: .leading)
        .padding()
    }
}

注意:使用push()和pop()管理光标时,务必成对调用,避免光标状态异常;多交互区域切换场景下,也可考虑使用NSCursor.set(),但push()/pop()更适合临时覆盖光标的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 09:40:25