繁体   English   中英

如何将swiftUI按钮连接到NSView操作?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM