【发布时间】:2019-06-08 21:12:15
【问题描述】:
我有一个 SwiftUI 应用程序的小开始。我正在尝试将按钮连接到已添加到 SwiftUI 主体的 NSView 中的操作。
我不知道如何在按钮的操作中引用 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)
}
}
【问题讨论】: