自定义'添加'视图动画到uistackview

时间:2016-01-18 21:46:39

标签: ios iphone animation uikit uistackview

uistackview animations

我正在玩iOS9 uistackview,在添加元素时自定义动画有问题。您可以注意到黄色元素位置从左上角开始动画,从零宽度开始。

我希望黄色元素已经位于紫色元素下方,并且只有从0到某个值的高度动画(绿色元素动画的反向行为)

我知道当元素已经在arrangeViews层次结构中时很容易做到,不幸的是在我的项目中我必须在任意索引处动态添加和删除项目。代码如下:

@interface ViewController ()
{
    NSLayoutConstraint* heightConstraint2;
    UIStackView *stackView;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];


    //View 1
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 60)];
    view1.backgroundColor = [UIColor blueColor];
    [view1.heightAnchor constraintEqualToConstant:60].active = true;
    [view1.widthAnchor constraintEqualToConstant:300].active = true;


    //View 2
    UIView *view2 = [[UIView alloc] init];
    view2.backgroundColor = [UIColor greenColor];
//    [view2.heightAnchor constraintEqualToConstant:100].active = true;
    [view2.widthAnchor constraintEqualToConstant:70].active = true;
    heightConstraint2 = [view2.heightAnchor constraintEqualToConstant:100];
    heightConstraint2.active = true;

    //View 3
    UIView *view3 = [[UIView alloc] init];
    view3.backgroundColor = [UIColor magentaColor];
    [view3.heightAnchor constraintEqualToConstant:100].active = true;
    [view3.widthAnchor constraintEqualToConstant:180].active = true;

    //Stack View
    stackView = [[UIStackView alloc] init];


    stackView.axis = UILayoutConstraintAxisVertical;
    stackView.distribution = UIStackViewDistributionEqualSpacing;
    stackView.alignment = UIStackViewAlignmentCenter;
    stackView.spacing = 0;


    [stackView addArrangedSubview:view1];
    [stackView addArrangedSubview:view2];
    [stackView addArrangedSubview:view3];

    stackView.translatesAutoresizingMaskIntoConstraints = false;
    [self.view addSubview:stackView];

}

-(void)viewDidAppear:(BOOL)animated {
    heightConstraint2.constant = 0;

    UIView *view4 = [[UIView alloc] init];
    view4.backgroundColor = [UIColor yellowColor];
    [view4.heightAnchor constraintEqualToConstant:80].active = true;
    [view4.widthAnchor constraintEqualToConstant:180].active = true;
    NSLayoutConstraint* heightConstraint4 = [view4.heightAnchor constraintEqualToConstant:0];
    [stackView insertArrangedSubview:view4 atIndex:3];
//    [stackView layoutIfNeeded];


    heightConstraint2.constant = 0;
    heightConstraint4.constant = 80;

    [UIView animateWithDuration:0.5
                          delay:3
                        options: UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         [stackView layoutIfNeeded];
                     }
                     completion:nil];

}

1 个答案:

答案 0 :(得分:2)

添加您的视图,但将其设置为hidden,然后在animationBlock中设置hidden = true