动画图像视图向上滑动

Wes*_*ick 8 animation cocoa-touch objective-c uiviewanimation ios

我试图使图像视图(logo下方)向上滑动100像素.我正在使用此代码,但根本没有任何反应:

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:3];
logo.center = CGPointMake(logo.center.x, logo.center.y - 100);
[UIView commitAnimations];
Run Code Online (Sandbox Code Playgroud)

此代码在viewDidLoad方法中.具体来说,logo.center = ...它不起作用.其他的事情(比如改变阿尔法)呢.也许我没有使用正确的代码向上滑动它?

Rob*_*Rob 41

对于非自动布局的故事板/ NIB,您的代码很好.顺便说一句,现在通常建议您使用块进行动画处理:

[UIView animateWithDuration:3.0
                 animations:^{
                     self.logo.center = CGPointMake(self.logo.center.x, self.logo.center.y - 100.0);
                 }];
Run Code Online (Sandbox Code Playgroud)

或者,如果您想要更多地控制选项等,您可以使用:

[UIView animateWithDuration:3.0
                      delay:0.0
                    options:UIViewAnimationCurveEaseInOut
                 animations:^{
                     self.logo.center = CGPointMake(self.logo.center.x, self.logo.center.y - 100);
                 }
                 completion:nil];
Run Code Online (Sandbox Code Playgroud)

但是如果你没有使用autolayout,那么你的代码应该可行.只是以上语法是iOS 4及更高版本的首选.

如果您正在使用自动布局,则(a)IBOutlet为您的垂直空间约束创建一个(见下文),然后(b)您可以执行以下操作:

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

    static BOOL logoAlreadyMoved = NO; // or have an instance variable

    if (!logoAlreadyMoved)
    {
        logoAlreadyMoved = YES; // set this first, in case this method is called again

        self.imageVerticalSpaceConstraint.constant -= 100.0;
        [UIView animateWithDuration:3.0 animations:^{
            [self.view layoutIfNeeded];
        }];
    }
}
Run Code Online (Sandbox Code Playgroud)

IBOutlet为约束添加一个,只需control在助理编辑器中从约束拖动到.h:

添加IBOutlet用于垂直约束

顺便说一句,如果您要为约束设置动画,请对您可能链接到该imageview的任何其他约束敏感.通常,如果你在图像下方放置一些东西,它会将其约束与图像相关联,因此你可能必须确保没有任何其他控件对图像有约束(除非你希望它们也移动) .

您可以通过打开故事板或NIB然后选择"文件检查器"(最右侧面板上的第一个选项卡,或者您可以通过按option+ command+ 1(数字"1")将其拉出来判断您是否使用自动布局) ):

自动布局

请记住,如果您计划支持iOS 6之前的版本,请务必关闭"自动布局".Autolayout是iOS 6的一项功能,不适用于早期版本的iOS.