当 UIImageView 触及屏幕上的特定点时,如何让事情发生?

How do I make something happen when a UIImageView hits certain points on the screen?

我有一个 UIImageView 用户可以拖动它。我希望当它击中(被拖过)屏幕上的某些点(从 x: 0 y: 0x: 0 y: 100 的所有点)时发生一些事情。

这是我目前使用的代码:

@IBOutlet var imageView: UIImageView!

var location = CGPoint(x: 0, y: 0)

override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
    var touch : UITouch! = touches.first as! UITouch
    location = touch.locationInView(self.view)
    imageView.center = location
}

func pointDetection() {
    if location == CGPoint(x: 0, y: 100) {
        println("1 Point!")
    } else {
        println("0 Points")
    }
}

你在问题中提到 "(从 x: 0 y: 0x: 0 y: 100 的所有点)" 但你的 if 陈述只是 true 对于一个特定点,CGPoint(x: 0, y: 100).

改成这样:

if location.y >= 0.0 && location.y <= 100.0 {
    println("1 Point!")
} else {
    println("0 Points")
}

我也没有看到您在哪里调用 pointDetection() 函数。将其添加到 touchesMoved.

您是指线而不是点吗?每次检查前一个点和新点是否位于你的线的两侧:

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesMoved:touches withEvent:event];

    CGPoint nowPoint = [[touches anyObject] locationInView:self.view];
    CGPoint prevPoint = [[touches anyObject] previousLocationInView:self.view];

    CGRect rect = CGRectMake(nowPoint.x, nowPoint.y, nowPoint.x + prevPoint.x, nowPoint.y + prevPoint.y);
    // then check if line intersects a rectangle
}

Here is example of intersects function