繁体   English   中英

Autolayout破坏了UIView Animation

[英]Autolayout breaks UIView Animation

努力使我的应用程序在iPhone 5和较小的iPhone之前工作。 很高兴要求iOS6并使用Autolayout因为它很好用。

但是,应用程序有4个按钮,可以定期交换位置,因此我为每个按钮分配一个与数组不同的位置,然后使用以下内容为动画设置动画:

[UIView animateWithDuration:0.5 animations:^{
    button1.center = [[locations objectAtIndex:0] CGPointValue];
    button2.center = [[locations objectAtIndex:1] CGPointValue];
    button3.center = [[locations objectAtIndex:2] CGPointValue];
    button4.center = [[locations objectAtIndex:3] CGPointValue];
}];

这不适用于Autolayout。 没有什么变化。 我得到的最好的是它会动画到一个位置,然后立即回弹。

当我删除Autolayout但是所有的按钮都在较小的iPhone上被碾碎,并且由于我使用的是iPhone 5尺寸设置的点,它们最终会降低,将底部行放在屏幕上。 我原来有来自Interface Builder的不同的CGPoint数字,但它们是“错误的”,虽然我认为它们是“错误的”,因为它们是Autolayout使用的数字。 数组就这样你可以看到:

buttonLocations = [NSArray arrayWithObjects:
        [NSValue valueWithCGPoint:CGPointMake(57, 523)],
        [NSValue valueWithCGPoint:CGPointMake(109, 523)],
        [NSValue valueWithCGPoint:CGPointMake(57, 471)],
        [NSValue valueWithCGPoint:CGPointMake(109, 471)],
        nil];

我该怎么做才能解决这个问题? 为每个尺寸的设备设置不同的点似乎不是很有效。

解决方案是您为items属性设置动画,而不是它的位置。

该位置将由autolayout设置,你不想打它。 但是,屏幕上的实际位置将是其“正确”(由自动布局设置)位置,由其变换属性抵消。

所以你可以说button.transform = CGTransformMake(x,y),它将从它的中心位置出现x和y。

有很多CGWhatever宏可以轻松地进行这些变换,你可以在动画块中更改它们来移动项目。

一种方法是使用自动布局系统,并为约束的“常量”值设置动画。 在下面的示例代码中,我在水平行中有三个按钮,每个按钮都有超前视图的前沿约束,这就是我的动画。 side1,side2和side3是这些约束的IBOutlets,button1,button2和button3是3个按钮的出口。

-(void)animateButton {
    [self.view removeConstraint:self.side1];
    [self.view removeConstraint:self.side2];
    [self.view removeConstraint:self.side3];

    NSLayoutConstraint *con1 = [NSLayoutConstraint constraintWithItem:self.button1 attribute:NSLayoutAttributeLeading relatedBy:0 toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1 constant:114];
    NSLayoutConstraint *con2 = [NSLayoutConstraint constraintWithItem:self.button2 attribute:NSLayoutAttributeLeading relatedBy:0 toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1 constant:213];
    NSLayoutConstraint *con3 = [NSLayoutConstraint constraintWithItem:self.button3 attribute:NSLayoutAttributeLeading relatedBy:0 toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1 constant:20];

    [self.view addConstraints:@[con1,con2,con3]];
    [UIView animateWithDuration:2 animations:^{
        [self.view layoutIfNeeded];
    }];
}

您可以通过代码中的少量更改来解决此问题。 而不是交换按钮位置,交换他们的布局约束。 您可以使用cocoapod SBP通过导入此类别来交换布局约束

    #import "UIViewController+SBP.h"

然后使用这种方法

    - (void)switchViewConst:(UIView*)firstView secondView:(UIView*)secondView durationInSeconds:(double)durationInSeconds

这是一个视频教程

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM