Jesper Kristiansen
Jesper Kristiansen

Reputation: 1959

SwiftUI - change cursor

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

Upvotes: 8

Views: 3650

Answers (1)

Raja Kishan
Raja Kishan

Reputation: 18914

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

Upvotes: 10

Related Questions