onContinuousHover

Adds an action to perform when the pointer enters, moves within, and exits the view's bounds.

View ModifieriOS 17.0+macOS 14.0+tvOS 17.0+onContinuousHover(coordinateSpace:perform:) in SwiftUI

Declaration

React
compose().onContinuousHover({
  coordinateSpace?: SwiftUI.CoordinateSpaceProtocol,
  perform: (arg0: SwiftUI.HoverPhase) => void,
})
Swift
nonisolated func onContinuousHover(
    coordinateSpace: some CoordinateSpaceProtocol = .local,
    perform action: @escaping (HoverPhase) -> Void
) -> some View

Parameters

Return value

A view that calls action when the pointer enters, moves within, or exits the view's bounds.

Discussion

Use this modifier to define a region for detecting pointer movement with a view. The following example updates a small rectangle's position and style by modifying hoverLocation and isHovering as the pointer moves within the larger, red rectangle:

@State private var hoverLocation: CGPoint = .zero
@State private var isHovering = false

var body: some View {
    Color.red
        .frame(width: 400, height: 400)
        .onContinuousHover { phase in
            switch phase {
            case .active(let location):
                hoverLocation = location
                isHovering = true
            case .ended:
                isHovering = false
            }
        }
        .overlay {
            Rectangle()
                .frame(width: 50, height: 50)
                .foregroundStyle(isHovering ? .green : .blue)
                .offset(x: hoverLocation.x, y: hoverLocation.y)
        }
}

See also

More in Events and lifecycle.