AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79479981
Accepted
Andrew
Andrew
Asked: 2025-03-03 08:51:21 +0800 CST2025-03-03 08:51:21 +0800 CST 2025-03-03 08:51:21 +0800 CST

如何制作一个“粘性” CircleView 并使其附着在 SwiftUI 中另一个视图的边缘?

  • 772

如何使某些点能够像视频中那样通过一组视图边缘进行拖动:

可通过一组视图拖动点

而不是自由拖拽:

自由可拖拽点

我甚至不知道从哪里开始,因为没有 GeometryReader 我就无法测量视图的边界。

然而,GeometryReader 在这种情况下并不合适,因为这些是位于不同图层上的不同视图。

示例视图:

struct ContentView: View {
    @State var point: CGPoint = .zero
    
    var body: some View {
        ZStack {
            //foreach Nodes
            NodeView()
            
            NodeView()
                .offset(x:0, y:100)

            //foreach Points
            BezierPoint(p1: $point)
        }
    }
}

struct NodeView : View {
    // var nodeViewModel: NodeViewModel
    // with exact location in space

    var body: some View {
        Text("Business")
            .multilineTextAlignment(.center)
            .foregroundStyle(.red)
            .shadow(color: .black, radius: 2 )
            .frame(minHeight: 40)
            .padding( EdgeInsets(horizontal: 20, vertical: 14) )
            .background {
                // ANY Shape can be here
                RoundedRectangle(cornerRadius: 10)
            }
    }
}

struct BezierPoint: View {
    @Binding var p1: CGPoint
    
    let pointsSize: CGFloat = 15
    
    var body: some View {
        GeometryReader { reader in
            ControlPointHandle(size: pointsSize)
                .offset( CGSize(width: p1.x + reader.size.width/2, height: p1.y + reader.size.height/2) )
                .gesture(
                    DragGesture()
                        .onChanged { value in
                            self.p1 = value.location.relativeToCenter(of: reader.size, minus: true)
                        }
                )
        }
    }
}


private struct ControlPointHandle: View {
    let size: CGFloat
    
    var body: some View {
        Circle()
            .frame(width: size, height: size)
            .overlay(
                Circle()
                    .stroke(Color.blue, lineWidth: 2)
            )
            .offset(x: -size/2, y: -size/2)
    }
}


fileprivate extension CGPoint {
    func relativeToCenter(of size: CGSize, minus: Bool = false) -> CGPoint {
        let a: CGFloat = minus ? -1 : 1
        return CGPoint(x: x + a * size.width/2, y: y + a * size.height/2)
    }
}

swift
  • 1 1 个回答
  • 71 Views

1 个回答

  • Voted
  1. Best Answer
    Benzy Neez
    2025-03-03T21:52:59+08:002025-03-03T21:52:59+08:00

    是否可以检测当前哪个视图位于 DragGesture 的位置下?答案中显示的技术可用于检测形状何时位于拖动点下(这是我的答案)。这GeometryReader在形状的背景中使用了,即使您有多层视图,它也应该有效。

    为了找到形状边缘上最接近拖动点的点,我建议采用以下方法:

    • 使用另一个答案中描述的点内框架技术确定拖动点是否靠近形状。
    • 如果拖动点靠近形状,则创建两条路径:
      1. 表示形状轮廓的路径。
      2. 一条由从形状中间穿过拖动点然后超越的线组成的路径。
    • 使用该Path函数lineIntersection(_:eoFill:)查找线与形状的交点。
    • 交点的最后一个点将是沿着形状边缘的点。

    您之前使用 包裹每个点GeometryReader。AGeometryReader很贪婪,会占用所有可用空间,因此这会使每个点的大小膨胀到父视图的完整大小。我建议不要这样做,而是使用.onGeometryChange来测量每个点的位置。

    以下是更新后的示例,以显示其工作原理。它包括第二个点,因此也可以测试这些点的独立性。

    import SwiftUI
    
    struct ContentView: View {
        @State private var dragLocation: CGPoint?
        @State private var contactPoint: CGPoint?
        @State private var nearestNodeId: Int?
        @State private var previousNodeId: Int?
        
        var body: some View {
            ZStack {
                ForEach(1...5, id: \.self) { i in
                    NodeView()
                        .background {
                            SplineContactDetector(nodeId: i,
                                                  shape:  .rect(cornerRadius: 10),
                                                  dragLocation: $dragLocation,
                                                  contactPoint: $contactPoint,
                                                  nearestNodeId: $nearestNodeId,
                                                  previousNodeId: $previousNodeId
                            )
                        }
                        .offset(x:0, y: CGFloat(i) * 100 - 400)
                }
                
                //foreach Points
                BezierPoint(dragLocation: $dragLocation, contactPoint: contactPoint)
                BezierPoint(dragLocation: $dragLocation, contactPoint: contactPoint)
                    .offset(x:0, y:100)
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color(red: 0.99, green: 0.94, blue: 0.76))
            .onChange(of: dragLocation) { _, newVal in
                if newVal == nil {
                    contactPoint = nil
                    nearestNodeId = nil
                    previousNodeId = nil
                }
            }
        }
    }
    
    /// ///////////////////
    /// Basic Views
    /// /////////////////
    
    struct BezierPoint: View {
        @Binding var dragLocation: CGPoint?
        let contactPoint: CGPoint?
        
        @State private var dragOffset: CGSize?
        @State private var currentOffset = CGSize.zero
        @State private var defaultFrame: CGRect?
        let pointsSize: CGFloat = 15
        
        private var offsetForContactPoint: CGSize? {
            if let contactPoint, let defaultFrame {
                CGSize(
                    width: contactPoint.x - defaultFrame.midX,
                    height: contactPoint.y - defaultFrame.midY
                )
            } else {
                nil
            }
        }
        
        private var offset: CGSize {
            let result: CGSize
            if let dragOffset {
                if let offsetForContactPoint {
                    result = offsetForContactPoint
                } else {
                    result = CGSize(
                        width: currentOffset.width + dragOffset.width,
                        height: currentOffset.height + dragOffset.height
                    )
                }
            } else {
                result = currentOffset
            }
            return result
        }
        
        var body: some View {
            Circle()
                .fill(.blue)
                .stroke(.primary, lineWidth: 2)
                .frame(width: pointsSize, height: pointsSize)
                .offset(offset)
                .gesture(
                    DragGesture(minimumDistance: 1, coordinateSpace: .global)
                        .onChanged { value in
                            dragOffset = value.translation
                            dragLocation = value.location
                        }
                        .onEnded { value in
                            if let offsetForContactPoint {
                                currentOffset = offsetForContactPoint
                            }
                            dragOffset = nil
                            dragLocation = nil
                        }
                )
                .onGeometryChange(for: CGRect.self) { proxy in
                    proxy.frame(in: .global)
                } action: { frame in
                    defaultFrame = frame
                }
        }
    }
    
    struct NodeView : View {
        var body: some View {
            Text("Business")
                .multilineTextAlignment(.center)
                .foregroundStyle(.red)
                .shadow(color: .black, radius: 2 )
                .frame(minHeight: 40)
                .padding( EdgeInsets(horizontal: 20, vertical: 14) )
                .background {
                    // ANY Shape can be here
                    RoundedRectangle(cornerRadius: 10)
                }
        }
    }
    
    /// ///////////////////
    /// Helpers
    /// /////////////////
    
    struct SplineContactDetector<S: Shape> : View {
        let nodeId: Int
        let shape: S
        
        @Binding var dragLocation: CGPoint?
        @Binding var contactPoint: CGPoint?
        @Binding var nearestNodeId: Int?
        @Binding var previousNodeId: Int?
        
        private let proximityMargin: CGFloat = 10
        
        var body: some View {
            GeometryReader { proxy in
                let frame = proxy.frame(in: .global)
                let proximity = proximity(nodeId: nodeId, frame: frame, shape: shape)
                
                Color.clear
                    .onChange(of: proximity) { _, newVal in
                        if newVal.isNearby {
                            if nearestNodeId != nodeId {
                                nearestNodeId = nodeId
                            }
                        } else if nearestNodeId == nodeId {
                            previousNodeId = nodeId
                            nearestNodeId = nil
                        }
                        if let nearestPoint = newVal.nearestPoint {
                            contactPoint = nearestPoint
                        }
                    }
            }
        }
            
        private func proximity(nodeId: Int, frame: CGRect, shape: S) -> ProximityInfo {
            let result: ProximityInfo
            if let dragLocation {
                let isNearby = frame
                    .insetBy(dx: -proximityMargin, dy: -proximityMargin)
                    .contains(dragLocation)
                if isNearby || (nearestNodeId == nil && previousNodeId == nodeId) {
                    let shapePath = shape.path(in: frame)
                    let joiningLine = Path { path in
                        path.move(to: CGPoint(x: frame.midX, y: frame.midY))
                        let dx = dragLocation.x - frame.midX
                        let dy = dragLocation.y - frame.midY
                        path.addLine(to: CGPoint(x: dx * 1000, y: dy * 1000))
                    }
                    let intersection = joiningLine.lineIntersection(shapePath)
                    result = ProximityInfo(isNearby: isNearby, nearestPoint: intersection.currentPoint)
                } else {
                    result = ProximityInfo(isNearby: false, nearestPoint: nil)
                }
            } else {
                result = ProximityInfo(isNearby: false, nearestPoint: nil)
            }
            return result
        }
        
        private struct ProximityInfo: Equatable {
            let isNearby: Bool
            let nearestPoint: CGPoint?
        }
    }
    

    动画片

    • 3

相关问题

  • IOS(模拟器)--> 本地 Vapor POST Image/png:Abort.413:有效负载太大

  • 在保存到 Core Data 之前调整图像大小

  • 如何在一个函数中快速处理两个完成处理程序

  • 为什么可编码键和值的字典本身不可编码?

  • 有没有办法将assertionFailure嵌入到'??'中 表达

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve