SwiftUI - usage of toggles - console logs: “invalid mode 'kCFRunLoopCommonModes'” - didSet does not work

放肆的年华 提交于 2020-03-03 09:43:40

问题


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. ;-)


回答1:


  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?")
        }
}


来源:https://stackoverflow.com/questions/60155947/swiftui-usage-of-toggles-console-logs-invalid-mode-kcfrunloopcommonmodes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!