Как подключить кнопку swiftUI к действию NSView? - PullRequest
1 голос
/ 09 июня 2019

У меня небольшое начало в приложении SwiftUI.Я пытаюсь подключить кнопку к действию в NSView, которое я добавил в тело SwiftUI.

Я не могу понять, как ссылаться на DrawingView внутри действия кнопки, чтобы я мог вызвать действие toggleDrawingType.Я не нашел документации для разработчиков, которая давала бы какие-либо подсказки относительно того, как это сделать.

------- ContentView.swift -------
import SwiftUI

struct ContentView : View {
    var body: some View {
        VStack {
            HStack {
                Text("Hello")
                Image("LineTool")
                Button(action: {}) {
                    Image("CenterCircleTool")
                }
            }
            DrawingView()
        }
    }
}

-------- DrawingView.swift --------

import SwiftUI

public struct DrawingView: NSViewRepresentable {
    public typealias NSViewType = DrawingViewImplementation

    public func makeNSView(context: NSViewRepresentableContext<DrawingView>) -> DrawingViewImplementation {
        return DrawingViewImplementation()
    }

    public func updateNSView(_ nsView: DrawingViewImplementation, context: NSViewRepresentableContext<DrawingView>) {
        nsView.setNeedsDisplay(nsView.bounds)
    }
}

enum DrawingType {
    case Rect
    case Circle
}

public class DrawingViewImplementation: NSView {

    var currentType = DrawingType.Rect

    override public func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        NSColor.blue.set()
        switch currentType {
        case .Rect:
            NSRect(x: 100, y: 100, width: 100, height: 100).frame()
        case .Circle:
            NSBezierPath(ovalIn: NSRect(x: 100, y: 100, width: 100, height: 100)).stroke()
        }
    }

    @IBAction func toggleDrawingType(sender: Any) {
        switch currentType {
        case .Rect:
            currentType = .Circle
        case .Circle:
            currentType = .Rect
        }
        setNeedsDisplay(bounds)
   }

    public override func mouseDown(with event: NSEvent) {
        toggleDrawingType(sender: self)
    }
}
...