admin管理员组

文章数量:1252720

GOAL I am trying to have a reliable way to detect if the cursor enters or exit the view.

PROBLEM It breaks when the window is zoomed or goes to full screen. After it is done resizing it will quickly set isHovering to false and then back to true. So you can't detect if the window is resizing and then skip the onHover, because it will fire after the resizing is done.

struct ContentView: View {
    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundStyle(.tint)
            Text("Hello, world!")
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .onHover { isHovering in
            print(isHovering)
        }
    }
}

#Preview {
    ContentView()
}

GOAL I am trying to have a reliable way to detect if the cursor enters or exit the view.

PROBLEM It breaks when the window is zoomed or goes to full screen. After it is done resizing it will quickly set isHovering to false and then back to true. So you can't detect if the window is resizing and then skip the onHover, because it will fire after the resizing is done.

struct ContentView: View {
    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundStyle(.tint)
            Text("Hello, world!")
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .onHover { isHovering in
            print(isHovering)
        }
    }
}

#Preview {
    ContentView()
}
Share Improve this question asked Jan 27 at 10:05 MarkMark 18.2k23 gold badges90 silver badges128 bronze badges 1
  • Have you considered using AppKit APIs to detect hover? Do they have the same problem? – Sweeper Commented Jan 27 at 13:37
Add a comment  | 

1 Answer 1

Reset to default 0

One work around seemed to be to put a debouncer between it.

@State private var onHoverPublisher = PassthroughSubject<Bool, Never>()
content
    .onHover { onHoverPublisher.send($0) }
    .onReceive(onHoverPublisher.debounce(for: .milliseconds(50), scheduler: DispatchQueue.main).removeDuplicates()) { isHovering in
        // This is hovering is more reliable.
    }

本文标签: swiftuiHow can I avoid onHover giving a false signal on macOS window resizeStack Overflow