So maybe I'm misunderstanding how SwiftUI works, but I've been trying to do this for over an hour and still can't figure it out.
struct ContentView: View, AKMIDIListener {
@State var keyOn: Bool = false
var key: Rectangle = Rectangle()
var body: some View {
VStack() {
Text("Foo")
key
.fill(keyOn ? Color.red : Color.white)
.frame(width: 30, height: 60)
}
.frame(width: 400, height: 400, alignment: .center)
}
func receivedMIDINoteOn(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel, portID: MIDIUniqueID? = nil, offset: MIDITimeStamp = 0) {
print("foo")
keyOn.toggle()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
So the idea is really simple. I have an external midi keyboard using AudioKit. When a key on the keyboard is pressed, the rectangle should change from white to red.
The receivedMIDINoteOn
function is being called and 'foo' is printed to the console, and despite keyOn.toggle()
appearing in the same function, this still won't work.
What's the proper way to do this?
Thanks
receivedMIDINoteOn
is called.ContentView
is a value, so if you pass somewhereContentView()
you just pass there a copy of view, which is different from that one which is drown in view hierarchy. Instead you have to useObservableObject
view model as listener. – Abernethymidi.addListener(contentView.keyboardObject)
, I get an error Expression type '()' is ambiguous. What is going on here? How do I use this observable object? – TruthDispatchQueue.main.async {}
in your callback to redirect to main queue. – Abernethy