Member-only story

The onHover View Modifier In SwiftUI

Detecting hover events in SwiftUI couldn’t be easier.

Gabriel Theodoropoulos
3 min readNov 25, 2022
Photo by Vojtech Okenka: https://www.pexels.com/photo/person-holding-apple-magic-mouse-392018/

View modifiers exist in SwiftUI in order to help us change the appearance and behavior of views easily. In the long list of them some work with particular views only and some other are intended to be used with any view. There are also quite common modifiers that we access often, while on the other edge there are less known ones existing for specific purposes.

Such a lesser common modifier is the onHover(_:). Its name suggests its purpose, which is no other than letting us know when a hover event occurs on a view. It's mostly useful in macOS applications, where the mouse cursor can go over the area occupied by a view.

To get to know this modifier, let’s go through a small sample application.

The demo app

The goal in this post is to build the following macOS application. It displays a few color views, presenting each color name when the mouse is above the matching view.

We’ll get started with the following custom type that stores a color’s data, as well as a hovered state; an indication whether…

--

--

Gabriel Theodoropoulos
Gabriel Theodoropoulos

Written by Gabriel Theodoropoulos

An iOS & macOS app maker writing code in Swift. Author of countless programming tutorials. Content creator. https://serialcoder.dev

No responses yet