首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >只有当你第一次触摸它时才移动的可拖式图像

问只有当你第一次触摸它时才移动的可拖式图像
EN

Stack Overflow用户
提问于 2014-07-28 03:28:44
回答 1查看 68关注 0票数 0

我正在制作一个游戏,在这个游戏中,你必须将一个图像拖过视图。我目前正在使用此代码来完成以下操作:

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

上面的代码的问题是,如果图像位于屏幕的右侧,我按下左边,图像将移动到我刚刚触摸到的左侧位置。我希望它是可拖动的,但只有当你首先按下图像,然后拖动它左右移动。因此,您首先必须按下屏幕右侧的图像,然后(将我的手指放在屏幕上)拖动到左边(或者我拖动手指的地方)。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-28 04:08:02

我发现的最简洁的方法是子类UIImageView,然后您所要做的就是:

代码语言:javascript
复制
#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如下所示:

代码语言:javascript
复制
#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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24988060

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档