0

I have a UIImageView that the user can drag around. I want something to happen when it hits (gets dragged over) certain points on the screen (all the points from x: 0 y: 0 to x: 0 y: 100).

This is the code I currently use:

@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")
    }
}
Daniel Storm
  • 18,301
  • 9
  • 84
  • 152
Se Mo
  • 21
  • 7

2 Answers2

0

You mention in your question "(all the points from x: 0 y: 0 to x: 0 y: 100)" but your if statement is only true for one specific point, CGPoint(x: 0, y: 100).

Change it to something like this:

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

I don't see where you're calling your pointDetection() function either. Add it to touchesMoved.

Daniel Storm
  • 18,301
  • 9
  • 84
  • 152
  • Oops yeah you're right, but i still get no reaction. – Se Mo May 25 '15 at 23:36
  • 1
    Wow thank you so much! I've literately been looking everywhere on how to do this and it just worked. I just started learning swift so this was very helpful. Thanks! – Se Mo May 25 '15 at 23:42
0

Did you mean the line instead point? Just every time check if previous and new point located on opposite sides of your line:

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

Community
  • 1
  • 1
aquarium_moose
  • 355
  • 1
  • 11