使用动画创建自定义视图

时间:2013-10-14 12:04:36

标签: ios objective-c animation uiview

我试图制作一个自定义视图,其中一个元素(UILabel)有动画,当点击自定义视图的按钮时,标签应该展开然后收缩。动画的第一部分正确发生但不是第二部分。我正在使用这种方法。

[UIView animateWithDuration:1.3 animations:^{
    CGRect frame = CGRectMake(50, 15, 140, 20);
    [labelFav setFrame:frame];
} completion:^(BOOL finished) {
    //[labelFav setHidden:YES];
    [UIView animateWithDuration:1.3 animations:^{
        CGRect frame = CGRectMake(50, 15, 0, 20);
        [labelFav setFrame:frame];
    }];

}];

我认为实现Refresh和LayoutSubviews方法的方法存在问题。 我是按照本教程ray wenderlinch

进行的

问题出现在调用第一个动画后,调用LayoutSubviews,因此所有项目都设置为初始位置,当第一个动画完成后,第二个动画开始但项目设置为原始状态,所以我相信动画不会发生,因为动画之间发生了变化。

我想知道如何正确实现这一点,你能帮我一把吗?

感谢。

PS:这是关于同一问题的第二个问题,但角度不同。my previous question

[UPDATE]

这是我的LayoutSubviews代码:

- (void)layoutSubviews {
[super layoutSubviews];

if(_idEvent == 0) return;

_buttonFav = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
[_buttonFav setImage:[UIImage imageNamed:@"fav.png"] forState:UIControlStateNormal];
[_buttonFav addTarget:self action:@selector(pressedFavButton:) forControlEvents:UIControlEventTouchDown];

_labelButton = [[UILabel alloc]initWithFrame:CGRectMake(0, 45, 0, 20)];
_labelButton.text = @"LABEL";

[self addSubview:_labelButton];
[self addSubview:_buttonFav];

}

在第二个动画之前调用它。我的刷新方法是:

- (void)refresh {
if(selected){

    [_buttonFav setImage:[UIImage imageNamed:@"fav_sel.png"] forState:UIControlStateNormal];
}
else{
    [_buttonFav setImage:[UIImage imageNamed:@"fav.png"] forState:UIControlStateNormal];
}

}

我只是根据一个属性设置按钮的图像,让我知道按钮是否被点击。

3 个答案:

答案 0 :(得分:1)

使用SetTransform和CGAffineTransform

试试这个

[UIView animateWithDuration:1.3 animations:^{

    [labelFav setTransform:CGAffineTransformMakeScale(0.5,0.5)];
} completion:^(BOOL finished) {

    [UIView animateWithDuration:1.3 animations:^{

        [labelFav setTransform:CGAffineTransformMakeScale(1.0,1.0)];
    }];

}];

答案 1 :(得分:1)

  

我这样做,如何使用自动布局制作动画呢?随着新的   XCode你没有选项来禁用它。

为标签添加宽度约束。然后在您的实现文件中为此约束创建IBOutlet(如果您不知道如何操作,请参阅the section 3. here),让我们说:

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *buttonWidthConstraint;

然后你可以用这种方式制作动画:

[UIView animateWithDuration:1.3 animations:^{
    self.buttonWidthConstraint.constant = 140;
    [self.view layoutIfNeeded];
} completion:^(BOOL finished) {

    [UIView animateWithDuration:1.3 animations:^{
        self.buttonWidthConstraint.constant = 0;
        [self.view layoutIfNeeded];
    }];

}];

答案 2 :(得分:0)

尝试将UILabel封装到UIView中并为该视图设置动画。

UIView *auxView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 100.0, 100.0)];
[auxView addSubview:labelFav];
[UIView animateWithDuration:1.3 animations:^{
    CGRect frame = CGRectMake(50, 15, 140, 20);
    [auxView setFrame:frame];
} completion:^(BOOL finished) {
    //[labelFav setHidden:YES];
        [UIView animateWithDuration:1.3 animations:^{
            CGRect frame = CGRectMake(50, 15, 10, 20);
            [auxView setFrame:frame];
        }];
}];
相关问题