Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 具有不同计时器的同一视图的多个实例_Objective C - Fatal编程技术网

Objective c 具有不同计时器的同一视图的多个实例

Objective c 具有不同计时器的同一视图的多个实例,objective-c,Objective C,我有一个名为“车”的自定义视图。我使用一个NSTimer来设置这个“汽车”视图的动画,它是以前添加到我的子视图中的 -(void)createRedCar { //-- here I create my first car [self.view addSubview:car]; //-- here I initiate a timer to move the car myTimer calls 'moveCar' method } 然后我可以用这种方法在屏幕上移动汽车 -(v

我有一个名为“车”的自定义视图。我使用一个NSTimer来设置这个“汽车”视图的动画,它是以前添加到我的子视图中的

-(void)createRedCar
{
  //-- here I create my first car
  [self.view addSubview:car];

  //-- here I initiate a timer to move the car
  myTimer calls 'moveCar' method
}
然后我可以用这种方法在屏幕上移动汽车

-(void)moveCar
{
car.transform //-- here I move the car across the screen
}
一切正常

我在创建“car”的新实例并完全像第一次那样设置它们的动画时遇到了困难。有什么想法吗

如果我再次尝试调用“createRedCar”方法,它只会在屏幕上添加一辆新车,而不会调用“moveCar”方法来设置动画

如何创建多个“汽车”视图并设置它们的动画


谢谢

问题在于将“移动”设置为所有汽车使用的变量。您可以按照以下方式进行操作:

- (void)createCar
{
    UIView *car = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 10)];
    [car setBackgroundColor:[UIColor redColor]];
    [self.view addSubview:car];

    [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(moveCarWithTimer:) userInfo:car repeats:YES];
}

- (void)moveCarWithTimer:(NSTimer *)timer
{
    UIView *carToMove = [timer userInfo];
    [carToMove setFrame:(CGRectMake(carToMove.frame.origin.x+1, 0, 40, 10))];
}

基于当前车辆的帧移动帧。我在一个新项目中尝试了这一点,每次我点击一个按钮,createCar都会被调用。只要您等待足够长的时间再次点击按钮,您就会看到新车与旧车分开运行。

问题在于将“移动”设置为所有车辆使用的变量。您可以按照以下方式进行操作:

- (void)createCar
{
    UIView *car = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 10)];
    [car setBackgroundColor:[UIColor redColor]];
    [self.view addSubview:car];

    [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(moveCarWithTimer:) userInfo:car repeats:YES];
}

- (void)moveCarWithTimer:(NSTimer *)timer
{
    UIView *carToMove = [timer userInfo];
    [carToMove setFrame:(CGRectMake(carToMove.frame.origin.x+1, 0, 40, 10))];
}

基于当前车辆的帧移动帧。我在一个新项目中尝试了这一点,每次我点击一个按钮,createCar都会被调用。只要您等待足够长的时间再次点击按钮,您就会看到新车与旧车分开运行。

您能看到我对这个问题的最新答案吗?它表明实际的codeuserInfo不能直接处理对象,只能通过NSDictionary。因此,是的,我按照您的建议通过了_carobject view NSDictionary,但不起作用,因为再次创建了_carobject,我将一直工作到再次调用“moveCarWithTimer”为止。我已经修改了答案,希望这会有所帮助。您能看到我对这个问题的最新答案吗?它表明实际的codeuserInfo不能直接处理对象,只能通过NSDictionary。因此,是的,我按照您的建议通过了_carobject view NSDictionary,但不起作用,因为再次创建了_carobject,我将一直工作,直到我再次调用“moveCarWithTimer”,我已经修改了答案,希望这会有所帮助。