ios - 横向拖放图像不起作用

标签 ios swift

我有以下代码可以将一个图像拖放到另一个图像上。

import Foundation
import UIKit

class DragImg: UIImageView {

    var originalPosition: CGPoint!
    var dropTarget: UIView?

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        originalPosition = self.center
    }

    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if let touch = touches.first {
            let position = touch.locationInView(self.superview)
            self.center = CGPointMake(position.x, position.y)
        }
    }

    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {

        if let touch = touches.first, let target = dropTarget {
            let position = touch.locationInView(self.superview)
            if CGRectContainsPoint(target.frame, position) {
                let notif = NSNotification(name: "onTargetDropped", object: nil)
                NSNotificationCenter.defaultCenter().postNotification(notif)
            }
        }
        self.center = originalPosition
    }   
}

在纵向模式下效果很好,但如果我更改为横向模式并尝试拖放图像,系统不会将图像识别为位于目标图像之上。您能解释一下原因并指出可能的解决方案吗?

最佳答案

如果没有看到更多的 View 层次结构,我不能准确地说出发生了什么,但是你说 selftarget 有不同的 super View 。这意味着它们的框架处于不同的坐标系中。每个 View 都定义了自己的坐标系。这些坐标系有时可能恰好对齐,旋转用户界面可能会改变两个 View 的坐标系是否对齐。

View 的 frame 仅在 View 的 superview 的坐标系中有意义。您正在计算 position = touch.locationInView(self.superview),因此 position 位于 self.superview 的坐标系中。那么你问的是 CGRectContainsPoint(target.frame, position),但是 target.frame 在不同的坐标系中,所以答案一般来说没有意义。

查看 touch 是否在 target 中的最简单方法是:

let position = touch.locationInView(target)
if target.pointInside(position, withEvent: event) {
    // The touch is in the target.
}

关于ios - 横向拖放图像不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36814128/

相关文章:

ios - 调用 addObject 时索引 0 超出空数组的范围?

ios - 两个如何防止加载苹果 map 和从 OSM MKTileOverlay 开始

Swift 3 - 如何从 FireBase 存储下载配置文件图像

ios - UITableView 嵌入容器 View 时在运行时不显示

ios - 在 Swift 或 Objective-C 中打印原始 HTTP 请求的便捷方式?

ios - 在 iTunes 中更改 iOS 应用名称

ios - Flutter 将 com.apple.security.network.client 添加到 *.entitlements

ios - 如何判断对象是不是 UIImage?

ios - 注销 iOS 应用程序后无法以不同用户身份登录

ios - 无法访问 WeatherKit