Swift UI not updating after drag event

Viewed 22

I am developing a Mac OS X Application using Xcode. I am not sure if I am using the right implementation but basically I made a blank new app and want to create a draggable circle which I intend to make a dial. I am able to add the view and I am able to track the drag location but the view isn't being updated. Any idea how to fix my code?


import SwiftUI

class ViewController: NSViewController{
    
    var metallicGradient: AngularGradient {
        let spectrum = [
            Color(NSColor.systemRed),
            Color(NSColor.systemBlue),
            Color(NSColor.systemGray),
            Color(NSColor.systemGray),
            Color(NSColor.systemGray),
            Color(NSColor.systemGray),
            Color(NSColor.systemGray),
            Color(NSColor.systemGray),
            Color(NSColor.systemGray),
            Color(NSColor.systemGray),
            Color(NSColor.systemGray),
            Color(NSColor.systemGray),
            Color(NSColor.systemGray),
        ]
        return AngularGradient(
            gradient: Gradient(colors: spectrum),
            center: .center,
            angle: .degrees(45)
        )
    }
    
    @State private var loc = CGPoint(x:1200, y:-300)
    @Published var obloc = CGPoint(x:1200, y:-300)

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.wantsLayer = true
        
        self.obloc = CGPoint(x:500, y:-444)
        
        Swift.print("Location is ", self.obloc)
        var subdial: some View {
            Circle()
                .fill(self.metallicGradient)
                .scaleEffect(0.95, anchor: .center)
                .frame(width: 200, height: 200)
                .position(self.obloc)
                .gesture(DragGesture()
                    .onChanged { value in
                        self.obloc = value.location
                        Swift.print(value.location, self.obloc)
                    }
                )
        }
        let newview = NSHostingView(rootView: subdial)
        view.addSubview(newview)
    }
    
    override func loadView() {
        self.view = NSView(frame: NSRect(x: 0, y: 0, width: NSScreen.main?.frame.width ?? 100, height: NSScreen.main?.frame.height ?? 100))
    }
    
}

0 Answers
Related