我正在制作一个游戏,你必须在视图中拖动图像。我目前正在使用此代码:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *mytouch = [[event allTouches] anyObject];
circle.center = [mytouch locationInView:self.view];
[self collision];
}
上面代码的问题在于,如果图像位于屏幕右侧并按下左侧,则图像将移动到我刚刚触摸的位置。我希望它可以拖动,但只有在你第一次按下图像然后拖动它时才会移动。因此,您首先要按下屏幕右侧的图像并(将手指放在屏幕上)向左拖动(或者拖动我的手指)。
答案 0 :(得分:1)
最简洁的方法是找到UIImageView
的子类,然后您需要做的就是:
#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
示例ViewController如下:
#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