UIView 动画中的 setFrame 不会移动,只会捕捉到位



在我的viewDidLoad方法中,我将一个按钮放置在视图的左侧,离开屏幕。

然后我用下面两种方法来制作动画:

-(void) viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self showButton];
}

方法:

-(void) showButton {
    [myButton setTitle:[self getButtonTitle] forState:UIControlStateNormal];
    // animate in
    [UIView beginAnimations:@"button_in" context:nil];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationDone)];
    [UIView setAnimationDuration:1.0];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [myButton setFrame:kMyButtonFrameCenter]; // defined CGRect
    [UIView commitAnimations];
}

按钮立即出现,不动。此外,animationDone选择器被立即调用。

为什么它不把我的按钮动画到屏幕上?

编辑:这必须与尝试在viewDidAppear中启动动画有关…

我试过你的动画代码,它工作得很好。

在哪里设置按钮的初始帧?是否有可能在开始动画之前错误地将按钮的帧设置为kMyButtonFrameCenter ?这就解释了为什么animationDone选择器会被立即调用。

下面是有效的代码:
-(void) showButton {
    UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [myButton setTitle:@"test" forState:UIControlStateNormal];
    myButton.frame = CGRectMake(-100.0, 100.0, 100.0, 30.0);
    [self.view addSubview:myButton];
    // animate in
    [UIView beginAnimations:@"button_in" context:nil];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationDone)];
    [UIView setAnimationDuration:1.0];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [myButton setFrame:CGRectMake(100.0, 100.0, 100.0, 30.0)]; 
    [UIView commitAnimations];
}

如你所见,我没有改变你的动画代码中的任何东西。所以我认为问题出在按钮的框架上。

有点跑题了:如果你还没有为iOS开发应用<4.你可能想看看iOS 4.0自带的UIView的"animation with blocks"。

[UIView animateWithDuration:1.0 delay:0.0 options:UIViewAnimationCurveEaseIn animations:^void{myButton.frame = kMyButtonFrameCenter} completion:^(BOOL completed){NSLog(@"completed");}];

=== EDIT ===

看了你的评论,看来我的怀疑是不正确的。Inspire48的答案指向了正确的方向。你应该把按钮的位置放在viewDidAppear方法或showButton方法中以确保按钮被放置在屏幕之外之前你调用动画

将动画调用放到viewDidAppear中。viewDidLoad用于更多的数据类型设置。任何视觉效果,比如动画,都应该放在viewDidAppear中。您已经确认了这一点—如果您稍等一下,它就可以工作。

最新更新