简体   繁体   中英

Draggable image that only moves if you first touch it

I am making a game in which you must drag an image across the view. I am currently using this code to do so:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *mytouch = [[event allTouches] anyObject];
    circle.center = [mytouch locationInView:self.view];
    [self collision];
}

The problem with the code above is that if the image is on the right side of the screen and I press down on the left, the image will move to the location I just touched on the left. I want it to be draggable, but only move if you first press down on the image, then drag it around. So you would first have to press down on the image on the right side of the screen and (keeping my finger on the screen) drag to the left (or wherever I drag my finger).

The most concise way to do this I've found is to subclass UIImageView , then all you have to do is this:

#import "MyImageView.h"

@implementation MyImageView

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self.superview];
    self.center = location;
}

@end

An example ViewController for this is as follows:

#import "ViewController.h"
#import "MyImageView.h"
#import <QuartzCore/QuartzCore.h>
#define NUM_IMAGES 50

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    const float radius = 15.0f;
    const float diameter = radius * 2;
    for (int i = 0; i < NUM_IMAGES; ++i)
    {
        float x = radius + drand48() * (self.view.frame.size.width - diameter - radius);
        float y = radius + drand48() * (self.view.frame.size.height - diameter - radius);
        MyImageView *imageView = [[MyImageView alloc] initWithFrame:CGRectMake(x, y, diameter, diameter)];
        imageView.backgroundColor = [UIColor colorWithRed:drand48()
                                                    green:drand48()
                                                     blue:drand48()
                                                    alpha:1.0f];
        imageView.userInteractionEnabled = YES;
        imageView.layer.cornerRadius = radius;
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0.f, 0.f, diameter, diameter)];
        label.text = [NSString stringWithFormat:@"%i", i + 1];
        label.textAlignment = NSTextAlignmentCenter;
        [imageView addSubview:label];
        [self.view addSubview:imageView];
    }
}

@end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM