我正在制作一个游戏,在这个游戏中,你必须将一个图像拖过视图。我目前正在使用此代码来完成以下操作:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *mytouch = [[event allTouches] anyObject];
circle.center = [mytouch locationInView:self.view];
[self collision];
}上面的代码的问题是,如果图像位于屏幕的右侧,我按下左边,图像将移动到我刚刚触摸到的左侧位置。我希望它是可拖动的,但只有当你首先按下图像,然后拖动它左右移动。因此,您首先必须按下屏幕右侧的图像,然后(将我的手指放在屏幕上)拖动到左边(或者我拖动手指的地方)。
发布于 2014-07-28 04:08:02
我发现的最简洁的方法是子类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];
}
}
@endhttps://stackoverflow.com/questions/24988060
复制相似问题