gpt4 book ai didi

swift - 将可拖动的 NSView 与 SwiftUI 组件相结合的问题

转载 作者:行者123 更新时间:2023-11-28 13:22:47 25 4
gpt4 key购买 nike

我有一个使用 Cocoa 编写的 NSView 类:

import Cocoa
import SwiftUI

final class EntityViewImpl: NSViewRepresentable {

func makeNSView(context: NSViewRepresentableContext<EntityViewImpl>) -> EntityView {
return EntityView(frame: NSRect(x: 0, y: 0, width: 100, height: 200))
}

func updateNSView(_ nsView: EntityView, context: NSViewRepresentableContext<EntityViewImpl>) {
// do nothing
}
}

class EntityView: NSView {

var oldMousePosition: NSPoint = .zero
var oldFrameOrigin: NSPoint = .zero

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

NSColor.white.setFill()
dirtyRect.fill()
}

override func mouseDown(with event: NSEvent) {
self.oldFrameOrigin = self.frame.origin
self.oldMousePosition = event.locationInWindow
}

override func mouseDragged(with event: NSEvent) {
let pointInSuperview = event.locationInWindow
self.frame.origin = NSPoint(x: oldFrameOrigin.x + (pointInSuperview.x - oldMousePosition.x),
y: oldFrameOrigin.y + (pointInSuperview.y - oldMousePosition.y))
}
}

我想在 SwiftUI View-body 中使用这个类,例如:

struct ContentView: View {

var body: some View {
Group {
EntityViewImpl()
.frame(width: 100, height: 100)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}

}

这很好用,我还可以在 EntityView 周围拖动。但是,我只能在其原始框架内“抓取”它。如果我将它拖到边界之外,鼠标事件将不再在原始框架之外的 View 部分触发。我是否必须以某种方式“告诉”ContentView NSView 已移动?

最佳答案

实际上如果你使用的是SwiftUI,你需要移动EntityView的superview,像这样:

override func mouseDown(with event: NSEvent) {
self.oldFrameOrigin = self.superview!.frame.origin
self.oldMousePosition = self.superview!.convert(event.locationInWindow, from: self)
}

override func mouseDragged(with event: NSEvent) {
let pointInSuperview = self.superview!.convert(event.locationInWindow, from: self)
self.superview!.frame.origin = NSPoint(x: oldFrameOrigin.x + (pointInSuperview.x - oldMousePosition.x),
y: oldFrameOrigin.y + (-pointInSuperview.y + oldMousePosition.y))
}

关于swift - 将可拖动的 NSView 与 SwiftUI 组件相结合的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58864703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com