[英]How to connect a swiftUI button to an NSView action?
我在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)
}
}
我遇到了同樣的問題,並在代碼的組織中找到了解決方案。
基本問題是,遵循NSViewRepresentable協議的結構本身不會發出對其底層NSView的引用。
解決方案是引入一個在創建ViewRepresentable結構時可用的對象。 在創建視圖時設置其對視圖的引用。
我的眼睛是更大的畫面的一部分,SwiftUI視圖不再包含視圖控制器。 SwiftUI視圖直接依賴於模型對象(通過@ObservableObject或@EnvironmentObject變量)。 因此,模型對象傾向於關心在視圖控制器執行之前(或視圖結構直接執行此功能)的功能。
我將模型對象交給ViewRepresentable的初始化程序,並在模型對象內為創建的視圖設置一個弱引用。 像這樣,內容對象是無所不在的實體-在ViewRepresentable和SwiftUI View結構中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.