Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - change cursor

Tags:

macos

swiftui

Edit: This works correct as mentioned by @Asperi. I need to use a View / Control, not a shape

I'm trying to change the cursor to a pointer when I hover over an element. I looked at this, but it doesn't work for me SwiftUI System Cursor

This is my code

struct CursorTestView: View {
    @State private var hover: Bool = false
    
    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 5)
                .fill(hover ? Color.green : Color.blue)
                .frame(width: 100, height: 50)
                .onHover(perform: { hovering in
                    self.hover = hovering
                    if (hover) {
                        NSCursor.pointingHand.push()
                    } else {
                        NSCursor.pop()
                    }
                })
        }
        .frame(width: 400, height: 400, alignment: .center)
        .background(Color.yellow.opacity(0.2))
    }
}

Any suggestion to what I'm missing ?

Thanks

like image 886
Jesper Kristiansen Avatar asked May 19 '26 23:05

Jesper Kristiansen


1 Answers

I notice the view is rendering 2 times so use the main queue.

struct CursorTestView: View {
    
    @State private var hover: Bool = false
    
    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 5)
                .fill(hover ? Color.green : Color.blue)
                .frame(width: 100, height: 50)
                .onHover { isHovered in
                    self.hover = isHovered
                    DispatchQueue.main.async { //<-- Here
                        if (self.hover) {
                            NSCursor.pointingHand.push()
                        } else {
                            NSCursor.pop()
                        }
                    }
                }
        }
        .frame(width: 400, height: 400, alignment: .center)
        .background(Color.yellow.opacity(0.2))
    }
}

It will also work if you do not update hover var.

enter image description here

like image 183
Raja Kishan Avatar answered May 22 '26 14:05

Raja Kishan