5

I have a general problem using toggles with SwiftUI. Whenever I use them I get this console error:

invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific - break on _CFRunLoopError_RunCalledWithInvalidMode to debug. This message will only appear once per execution.

In addition to this didSet does not print anything when I hit the toggle in the simulator. Does anyone have an idea, or is it a SwiftUI bug?

Other related questions on StackOverflow which are some month old didn't seem to find a solution.

import SwiftUI


struct ContentView: View {

    @State private var notifyCheck = false {
        didSet {
            print("Toggle pushed!")
        }
    }

    var body: some View {
            Toggle(isOn: $notifyCheck) {
                Text("Activate?")
            }
    }
}

If this is a bug, I wonder what the workaround for toggles is. It's not as if I would be the first person using toggles in iOS. ;-)

Kuhlemann
  • 3,066
  • 3
  • 14
  • 41
  • like it's a bug somewhere in the UISwitch code in Xcode 11, It's happening in UIKit too – Mac3n Feb 10 '20 at 18:12

1 Answers1

10
  1. Ignore that warning, it's SwiftUI internals and does not affect anything. If you'd like submit feedback to Apple.

  2. didSet does not work, because self here (as View struct) is immutable, and @State is just property wrapper which via non-mutating setter stores wrapped value outside of self.

Update: do something on toggle

@State private var notifyCheck = false

var body: some View {

        let bindingOn = Binding<Bool> (
           get: { self.notifyCheck },
           set: { newValue in
               self.notifyCheck = newValue
               // << do anything
           }
        )
        return Toggle(isOn: bindingOn) {
            Text("Activate?")
        }
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • Thanks for the information! Is there an easy way to implement a functionality which has the result that I tried to achive with above code (toggle triggered on-> do something)? – Kuhlemann Feb 10 '20 at 19:43
  • Thanks a lot! Your code just misses an "," : get: { self.notifyCheck }, – Kuhlemann Feb 11 '20 at 17:53