以下是测试项目中主视图控制器的viewDidLoad:
- (void)viewDidLoad
{ [super viewDidLoad];
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 300, 300)];
[self.view addSubview:containerView];
UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
[redView setBackgroundColor:[UIColor redColor]];
[containerView addSubview:redView];
UIView *yellowView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
[yellowView setBackgroundColor:[UIColor yellowColor]];
[UIView transitionWithView:containerView duration:3
options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
[redView removeFromSuperview];
[containerView addSubview:yellowView];
}
completion:NULL];
}
出现黄色框。没有动画,无论我尝试哪种UIViewAnimationOption。为什么???
编辑:我也尝试使用performSelector withDelay将动画移出viewDidLoad并转移到另一个方法中。相同的结果 - 没有动画。
还试过这个: [UIView transitionFromView:redView toView:yellowView持续时间:3个选项:UIViewAnimationOptionTransitionFlipFromLeft completion:NULL];
然而,黄色视图刚刚出现。没有动画。
答案 0 :(得分:6)
经过一些测试后,您似乎无法创建容器视图并在同一个runloop中设置动画并使其工作正常。为了使您的代码有效,我首先在containerView
方法中创建了redView
和viewDidLoad
。然后我将动画放入viewDidAppear
方法。因此,我可以从containerView
方法引用redView
和viewDidAppear
,我将它们作为属性。以下是将执行您想要的动画的ST_ViewController.m
文件的代码。
@interface ST_ViewController ()
@property (nonatomic, strong) UIView *containerView;
@property (nonatomic, strong) UIView *redView;
@end
@implementation ST_ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self setContainerView:[[UIView alloc] initWithFrame:CGRectMake(10, 10, 300, 300)]];
[[self view] addSubview:[self containerView]];
[self setRedView:[[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)]];
[[self redView] setBackgroundColor:[UIColor redColor]];
[[self containerView] addSubview:[self redView]];
}
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
UIView *yellowView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
[yellowView setBackgroundColor:[UIColor yellowColor]];
[UIView transitionWithView:[self containerView]
duration:3
options:UIViewAnimationOptionTransitionFlipFromLeft
animations:^(void){
[[self redView] removeFromSuperview];
[[self containerView] addSubview:yellowView];
}
completion:nil];
}
@end
答案 1 :(得分:1)
请勿将其放入viewDidLoad
。当视图完全加载到内存中但尚未显示在屏幕上时,将调用viewDidLoad
。
尝试将上述代码放在viewDidAppear:
中,当视图在屏幕上显示时调用该代码
编辑:旁注,如果performSelector:withDelay:修复了一些东西,那就意味着你试图做错了。你需要以某种方式重构。 performSelector:withDelay:99.999%的时间是解决问题的错误方法。只要将此代码放在不同的速度设备(新的iPhone,旧的iPhone)上,它就会搞砸。