UIView transitionWithView不起作用

这里是testing项目中主视图控制器的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]; } 

黄色框出现。 没有animation,不pipe我尝试使用哪个UIViewAnimationOption。 为什么???

编辑:我也尝试使用performSelector withDelay将animation从viewDidLoad移出到另一个方法。 同样的结果 – 没有animation。

也试过这个:[UIView transitionFromView:redView toView:yellowView duration:3 options:UIViewAnimationOptionTransitionFlipFromLeft completion:NULL];

不过,黄色的视图刚刚出现。 没有animation。

经过一些testing,看起来你不能创build容器视图,并在同一个runloop中设置animation,并有事情的工作。 为了使你的代码工作,我首先在viewDidLoad方法中创build了containerViewredView 。 然后我把你的animation放到viewDidAppear方法中。 所以我可以从viewDidAppear方法引用containerViewredView ,我使它们成为属性。 这里是一个ST_ViewController.m文件的代码,它将执行你想要的animation。

 @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 

不要把它放在viewDidLoadviewDidLoad在视图完全加载到内存中时调用,但尚未显示在屏幕上。

尝试把上面的代码放在viewDidAppear:当视图出现在屏幕上时调用它。

编辑:一个侧面说明,如果performSelector:withDelay:修复了一些东西,这意味着你正在尝试做错的事情。 你需要以某种方式重构。 performSelector:withDelay:99.999%的时间是解决问题的错误方法。 只要你把这个代码放在一个不同的速度设备(新的iPhone,旧的iPhone)上就会搞砸了。