如何在触摸屏幕时创建图像然后可以移动它

时间:2014-08-07 06:11:07

标签: ios touchesbegan touchesmoved

我试图在触摸屏幕时创建一个点,然后能够移动该点,然后结束触摸,这将显示警报视图。对于第一次触摸和移动,到目前为止我有这个代码...

{
    UIImageView *dot =[[UIImageView alloc] initWithFrame:CGRectMake(359,487,50,50)];
    dot.image=[UIImage imageNamed:@"hockey-puck-stress-toy-superextralarge-175648.png"];
    [self.view addSubview:dot];
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:touch.view];
    dot.center = location;
}

-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self touchesBegan:touches withEvent:event];
}

问题是,这会在移动时创建一个新对象,而不是在我第一次触摸它时。我明白为什么会这样做,但我不知道如何解决它。有人可以帮忙吗?谢谢!

1 个答案:

答案 0 :(得分:0)

在.h文件中创建一个属性:

@property (nonatomic) UIImageView *dot;

然后只是创建视图,如果它不存在,然后移动属性:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    if (!self.dot) {
        UIImageView *dot =[[UIImageView alloc] initWithFrame:CGRectMake(359,487,50,50)];
        dot.image=[UIImage imageNamed:@"hockey-puck-stress-toy-superextralarge-175648.png"];
        [self.view addSubview:dot];
    }
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:touch.view];
    self.dot.center = location;
}