多个 NSTimer 动画视图
Multiple NSTimer animation views
- (void)createCar
{
_car = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 10)];
[_car setBackgroundColor:[UIColor redColor]];
[self addSubview:_car];
_myTimer = [NSTimer scheduledTimerWithTimeInterval:normalSpeedValue target:self selector:@selector(moveCar) userInfo:nil repeats:YES];
}
- (void)moveCar
{
static int move = 0;
move = move+1;
[_car setFrame:(CGRectMake(move, 0, 40, 10))];
}
这就是我创建视图并为其从左向右移动设置动画的方式。
如果我再次调用方法 "createCar",它只会创建一个新视图,但不会设置动画。这是为什么?
我希望能够创建更多视图并制作动画 (moveCar)。
对 createCar
的额外调用创建静止但仍然可见的汽车的原因是因为计时器 moveCar
上的回调仅引用存储在_car
伊娃.
过去创建的汽车仍然可见,因为它们被添加到的视图仍然引用它们并因此继续绘制它们。
您可以通过为您的汽车创建一个 NSMutableArray
,将它们添加到 createCar
中,然后在 moveCar
方法中循环移动每辆汽车来解决此问题。
示例代码:
// ...
NSMutableArray<UIView *> *_cars; // Be sure to init this somewhere
// ...
// ...
timer = NSTimer.schedule ... // Schedule time in viewDidLoad, or somwhere
// ...
- (void)createCar
{
UIView *_car = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 100, 100)];
[_car setBackgroundColor: [UIColor redColor]];
[self.view addSubview: _car];
[_cars addObject:_car];
}
- (void)moveCars
{
// go through each car
[_cars enumerateObjectsUsingBlock:^(UIView *car, NSUInteger i, BOOL *stop) {
// and set its frame.x + 1 relative to its old frame
[car setFrame: CGRectMake(car.frame.origin.x + 1, 0, 100, 100)];
}];
}
这是一种简单的方法。但是如果你想要灵活性,比如不同的车有不同的速度,那就需要一些修改,但不会太多。
希望对您有所帮助!
每次当方法被调用时你的移动变为0。将其声明为实例变量并在 createCar
方法中将其初始值设置为 0(在您的情况下)。我想这就是你想要的。希望这会有所帮助:)
- (void)createCar
{
_car = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 10)];
[_car setBackgroundColor:[UIColor redColor]];
[self addSubview:_car];
_myTimer = [NSTimer scheduledTimerWithTimeInterval:normalSpeedValue target:self selector:@selector(moveCar) userInfo:nil repeats:YES];
}
- (void)moveCar
{
static int move = 0;
move = move+1;
[_car setFrame:(CGRectMake(move, 0, 40, 10))];
}
这就是我创建视图并为其从左向右移动设置动画的方式。
如果我再次调用方法 "createCar",它只会创建一个新视图,但不会设置动画。这是为什么?
我希望能够创建更多视图并制作动画 (moveCar)。
对 createCar
的额外调用创建静止但仍然可见的汽车的原因是因为计时器 moveCar
上的回调仅引用存储在_car
伊娃.
过去创建的汽车仍然可见,因为它们被添加到的视图仍然引用它们并因此继续绘制它们。
您可以通过为您的汽车创建一个 NSMutableArray
,将它们添加到 createCar
中,然后在 moveCar
方法中循环移动每辆汽车来解决此问题。
示例代码:
// ...
NSMutableArray<UIView *> *_cars; // Be sure to init this somewhere
// ...
// ...
timer = NSTimer.schedule ... // Schedule time in viewDidLoad, or somwhere
// ...
- (void)createCar
{
UIView *_car = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 100, 100)];
[_car setBackgroundColor: [UIColor redColor]];
[self.view addSubview: _car];
[_cars addObject:_car];
}
- (void)moveCars
{
// go through each car
[_cars enumerateObjectsUsingBlock:^(UIView *car, NSUInteger i, BOOL *stop) {
// and set its frame.x + 1 relative to its old frame
[car setFrame: CGRectMake(car.frame.origin.x + 1, 0, 100, 100)];
}];
}
这是一种简单的方法。但是如果你想要灵活性,比如不同的车有不同的速度,那就需要一些修改,但不会太多。
希望对您有所帮助!
每次当方法被调用时你的移动变为0。将其声明为实例变量并在 createCar
方法中将其初始值设置为 0(在您的情况下)。我想这就是你想要的。希望这会有所帮助:)