Search code examples
swiftuitooltip

Custom ToolTip in swiftUI for iOS


I have a row of colors and I want to display a ToolTip for each of the colors.

struct ColorsView: View {
    let colors = [UIColor.red, UIColor.white, UIColor.gray, UIColor.blue, UIColor.black]
    var body: some View {
        HStack {
            ForEach(0..<colors.count) { index in
                Color(self.colors[index])
                .frame(width: (UIScreen.main.bounds.size.width - 30) / 5, height: 25)
            }
        }.cornerRadius(12)
    }
}

How can I create a custom toolTip for this? I tried wrapping in a ZStack but this doesn't seem to solve the problem exactly. Any help :)


Solution

  • You can also try using this tool: https://github.com/quassummanus/SwiftUI-Tooltip

    Here's an example of how you could use it with a simple Text view, you can extrapolate from there. It's very nice because it doesn't rely on any Apple-provided APIs that are not fundamental to SwiftUI, so you can use it on all platforms.

    Text("Say something nice...")
        .tooltip(.bottom) {
            Text("Something nice!")
        }
    

    And you get something like this:

    example