簡體   English   中英

UIView transitionWithView不起作用

[英]UIView transitionWithView doesn't work

這是測試項目中主視圖控制器的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 duration:3選項:UIViewAnimationOptionTransitionFlipFromLeft completion:NULL];

盡管如此,黃色視圖才會出現。 沒有動畫。

經過一些測試后,您似乎無法創建容器視圖並在同一個runloop中設置動畫並使其工作正常。 為了使代碼有效,我首先在viewDidLoad方法中創建了containerViewredView 然后我將你的動畫放入viewDidAppear方法。 因此我可以從viewDidAppear方法引用containerViewredView ,我將它們作為屬性。 以下是將執行所需動畫的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

不要把它放在viewDidLoad 當視圖完全加載到內存中但尚未顯示在屏幕上時,將調用viewDidLoad

嘗試將上面的代碼放在viewDidAppear:當視圖出現在屏幕上時調用。

編輯:旁注,如果performSelector:withDelay:修復了一些東西,這意味着你試圖做錯了。 你需要以某種方式重構。 performSelector:withDelay:99.999%的時間是解決問題的錯誤方法。 只要將此代碼放在不同的速度設備(新的iPhone,舊的iPhone)上,它就會搞砸。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM