gpt4 book ai didi

ios - 可拖动图像,只有在您第一次触摸它时才会移动

转载 作者:行者123 更新时间:2023-11-29 02:47:02 25 4
gpt4 key购买 nike

我正在制作一款游戏,您必须在其中拖动图像穿过 View 。我目前正在使用此代码来执行此操作:

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

关于ios - 可拖动图像,只有在您第一次触摸它时才会移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24988060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com