ios - 从 ScrollView 中拖出一个项目

标签 ios swift uiscrollview

尝试从 UIScrollView 中拖动项目并将其放在第二个 UIScrollView 上时,我的路径是否正确?这两个 UIScrollView 最终都不会改变,但我想让图像跟随 touchMoved 位置,直到它在第二个 UIScrollView 上释放。

我扩展了 UIScrollView,以便可以看到 UIScrollView 内触摸开始的位置。

extension UIScrollView {
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.next?.touchesBegan(touches, with: event)
    print("touchesBegan")
    }
}

获取触摸的对象

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    if let touch = touches.first {
        beginningLocation = touch.location(in: self.view)
        let position = touch.location(in: itemScrollview)
        print("itemScrollview: \(position)")

        let whoHit = Int(position.x / 120)
        print("whoHit: \(whoHit) \(GameData.items[whoHit].name)")
    }
}

我试图使用touchesEnded来查看用户是否向上拖动,但touchesEnded并不总是被调用。如果触摸在同一个 UIScrollView 上开始和结束,则有效,但是当拖离时,touchesEnd 不会被调用。

最佳答案

您无法“直接”将对象( View 、 ImageView 、标签、按钮等)从一个 View 拖动到另一个 View (无论是 UIView 或 UIScrollView 还是任何其他容器)。

相反,您需要将要拖动的对象从包含 View “移动”到 super View (“主” View ),将其作为主视图的 subview 拖动,然后检查它在哪里已发布。

所以,本质上,如果你想拖动 UIImageView:

  • 第一次触摸时,将 ImageView 从其包含 View 移动到“主” View
  • 平移坐标,使它们现在相对于“主” View
  • 跟踪主视图坐标中的触摸/拖动,随时重新定位 ImageView
  • 释放时,查看结束触摸是否位于“目标”容器 View 内
  • 如果是,则将 ImageView 添加为目标 View 的 subview (转换位置坐标)
  • 如果它不在目标框架内,请将其添加回其原始容器,或将其放入主视图中,或蒸发它,或任何您想要的。

关于ios - 从 ScrollView 中拖出一个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47161542/

相关文章:

ios - 循环遍历 UIScrollView 并设置 UImageView

objective-c - 在当前 View 中访问 subview

ios - 每个 UI 元素都应该有一个 IBOutlet 吗?

ios - 使用 SwiftUI 获取 AVPlayerItem 轨道标题

ios - 每天固定时间运行一个任务

swift - 在 swift 中的选项中隐藏 ECSlidingViewController 中的菜单栏

uiscrollview - EXC_Breakpoint ScrollView 崩溃

ios - 如何正确使用时区

ios - 如何摆脱按下后退按钮后立即发生的故障?

ios - UIScrollView 禁用顶部弹跳