我正在我的应用中动态创建UIButton。当我显示按钮时,我想为它们制作动画。我似乎无法通过此代码获取动画按钮:
UIImage *buttonBackground = [UIImage imageNamed:@"ButtonRed.png"];
for (NSInteger x = 0; x < 4; x++) {
CGRect btnFrame = CGRectMake(x * (buttonBackground.size.width+2),
y * (buttonBackground.size.height + 1),
buttonBackground.size.width,
buttonBackground.size.height);
UIButton *gridButton = [[[UIButton alloc] initWithFrame: btnFrame] retain];
[gridButton setBackgroundImage:buttonBackground forState:UIControlStateNormal];
[buttonBackground release];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:.5];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:gridButton cache:YES];
[self.view addSubview:gridButton];
[UIView commitAnimations];
[gridButton release];
}
如果我将“forView:gridButton”更改为“forView:self.view”,则整个视图会翻转,但不会翻转单个按钮。我只想让每个按钮翻转。
感谢您的帮助。
答案 0 :(得分:0)
在您将+[UIView setAnimationTransition: forView:cache:]
作为forView:
参数调用{{1}}之前,该视图必须可见。
重新排列,以便将按钮添加到父视图,然后调用动画
答案 1 :(得分:0)
非常感谢你的建议,rpetrich。它让我思考正确的方向。
似乎动画不会在每个按钮的for循环内运行。我试图在beginAnimations调用中包装整个FOR循环,但这也不起作用。
我对rpetrich建议的performSelector命令并不十分熟悉,但我想我可以使用计时器。
我终于能够通过将所有动态创建的按钮设置为在FOR循环中首先隐藏,然后在FOR循环外部创建一个在执行动画时取消隐藏它们的计时器来设置按钮的动画。
以下是我所做的代码更改:
UIImage *buttonBackground = [UIImage imageNamed:@"ButtonRed.png"];
for (NSInteger x = 0; x < 4; x++) {
CGRect btnFrame = CGRectMake(x * (buttonBackground.size.width+2),
y * (buttonBackground.size.height + 1),
buttonBackground.size.width,
buttonBackground.size.height);
UIButton *gridButton = [[[UIButton alloc] initWithFrame: btnFrame] retain];
[gridButton setBackgroundImage:buttonBackground forState:UIControlStateNormal];
[buttonBackground release];
// ****** I took out all animation code ******
[self.view addSubview:gridButton];
gridButton.hidden = YES; // <----------- ****** new code ******
[gridButton release];
}
// **** the following code was added just outside the FOR loop to create timer that will animate buttons as they're un-hidden.
// NSTimer gridTimer is created in the header file.
gridTimer = [NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(showGrid) userInfo:nil repeats:NO];
这是我用计时器调用的新方法:
-(void) showGrid{
for (UIButton *obj in self.view.subviews) {
if ([obj isMemberOfClass:[UIButton class]]) {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:obj cache:YES];//~~self.view cache:YES];
obj.hidden = NO;
[UIView commitAnimations];
}
}
[gridTimer invalidate];
}