横向拖放图像不起作用



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

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
    }   
}

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

如果不看到更多视图层次结构,我无法准确说出正在发生的事情,但您说selftarget有不同的超级视图。这意味着它们的帧位于不同的坐标系中。每个视图定义自己的坐标系。这些坐标系有时可能会对齐,旋转用户界面可能会更改两个视图的坐标系是否对齐。

视图的frame仅在视图superview的坐标系中有意义。你正在计算position = touch.locationInView(self.superview),所以positionself.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.
}

我已经找到了一个解决方案,但我想了解它是如何工作的,所以如果有人可以解释我为什么这样做,我将不胜感激。我找到的解决方案是:更改了此内容:

let position = touch.locationInView(self.superview)

对此:

let position = touch.locationInView(touch.view!.window)

.

最新更新