1

How to I apply a hueRotation, blur, or other effect to a control in SwiftUI and still allow users to interact with it?

import SwiftUI

struct SwiftUIView: View {
    @State var isOn = true
    var body: some View {
        Toggle(isOn: $isOn) {
            Text("The toggle is \(isOn ? "on" : "off")")
        }
            .padding()
            .hueRotation(.degrees(60)) // <-- Disables interactivity
    }
}

struct SwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
        SwiftUIView()
    }
}
  • you can use .onTapGesture – Jawad Ali Dec 30 '19 at 10:05
  • like this link https://izakpavel.github.io/development/2019/09/30/animating-gradients-swiftui.html – Jawad Ali Dec 30 '19 at 10:05
  • Using mentioned modifiers you convert control into flat view, just in case. To modify control it should be used either `*style`s, where possible, or `.appearance()` where applicable. – Asperi Dec 30 '19 at 11:56
  • @jawadAli .onTapGesture + withAnimation gets about halfway there, but that leaves the control with no haptic feedback and no dragging behavior. – Spencer Connaughton Dec 31 '19 at 00:55
  • @Asperi, I don't understand your comment. Can you rephrase? – Spencer Connaughton Dec 31 '19 at 00:55
  • `Toggle` is a control, but `Toggle.hueRotation()` is not a control in `hue rotation` view, it is just hue rotation view (actually image). You cannot make it back behave like a `Toggle`. – Asperi Dec 31 '19 at 06:04

1 Answers1

0

The unfortunate answer is that this appears to be a bug in UIKit backed Views (SwiftUI's Toggle is actually using UISwitch on iOS). If you modify your code to use something with pure SwiftUI interactivity will work.

struct SwiftUIView: View {
    @State var isOn = true
    var body: some View {
        HStack {
            Button("Toggle") {
                self.isOn.toggle()
            }
            Text("Is On: \(self.isOn ? "yes" : "no")")
        }
            .padding()
            .hueRotation(.degrees(60)) // <-- Interactivity still works
            .contentShape(Rectangle())
    }
}

You should file feedback.

Obviously, you would like to style this Toggle. There are some solutions in this question, though none of them are very satisfying.

arsenius
  • 12,090
  • 7
  • 58
  • 76