[英]Draggable image that only moves if you first touch it
我正在制作一個游戲,其中您必須在視圖上拖動圖像。 我目前正在使用此代碼執行此操作:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *mytouch = [[event allTouches] anyObject];
circle.center = [mytouch locationInView:self.view];
[self collision];
}
上面代碼的問題是,如果圖像位於屏幕的右側,而我按下左側,則圖像將移動到我剛剛觸摸左側的位置。 我希望它是可拖動的,但是只有在您首先按下圖像然后在周圍拖動時才移動。 因此,您首先必須按下屏幕右側的圖像,然后(將手指保持在屏幕上)向左拖動(或在我拖動手指的任何位置)。
我發現最簡單的方法是將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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.