UIView动画上

时间:2020-12-11 08:30:11

主要参考:http://blog.csdn.net/huifeidexin_1/article/details/7597868  http://www.2cto.com/kf/201409/335661.html

如果动画不放在按钮事件中,直接放到viewDidLoad里,程序首先执行这个controller,这时动画是不会显示的,原因:出现这个问题是因为开机时候系统有个动画,系统动画和这个动画重复了,解决方案:

1.将动画写在按钮事件中

2.利用定时器

//
//  ViewController.m
//  动画
//
//  Created by City--Online on 15/4/1.
//  Copyright (c) 2015年 City--Online. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
{
    UIButton *btn;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    btn=[UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame=CGRectMake(30, 30, 50, 50);
    btn.backgroundColor=[UIColor redColor];
    [btn setTitle:@"按钮" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnclick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];

}
-(void)btnclick:(id)sender
{
    //开启一个动画 事务型
    [UIView beginAnimations:@"test" context:nil];
    //设置动画延迟执行时间 单位秒
    [UIView setAnimationDelay:0];
     //设置动画块中的动画效果是否自动重复播放
    [UIView setAnimationRepeatAutoreverses:YES];
    //设置动画重复的次数
    [UIView setAnimationRepeatCount:0];
     //设置代理 未设置的时候下面的setAnimationDidStopSelector、setAnimationWillStartSelector不起作用
    [UIView setAnimationDelegate:self];
    //设置动画开始的方法
    [UIView setAnimationDidStopSelector:@selector(viewstop)];
    //设置动画结束时的方法
    [UIView setAnimationWillStartSelector:@selector(viewstart)];
    /*typedef NS_ENUM(NSInteger, UIViewAnimationTransition) {
        UIViewAnimationTransitionNone,
        UIViewAnimationTransitionFlipFromLeft, //左翻转
        UIViewAnimationTransitionFlipFromRight,//右翻转
        UIViewAnimationTransitionCurlUp,       //向上折转
        UIViewAnimationTransitionCurlDown,     //向下折转
    };*/
    [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.view cache:YES];
    //设置动画曲线,控制动画速率 枚举类型
    /*typedef NS_ENUM(NSInteger, UIViewAnimationCurve) {
        UIViewAnimationCurveEaseInOut,         // slow at beginning and end
        UIViewAnimationCurveEaseIn,            // slow at beginning
        UIViewAnimationCurveEaseOut,           // slow at end
        UIViewAnimationCurveLinear
    };*/
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    CGRect frame=btn.frame;
    if (frame.origin.x<self.view.frame.size.width-20) {
        frame.origin.x+=20;
    }
    else
    {
        frame.origin.x=0;

    }
    btn.frame=frame;
    btn.backgroundColor=[UIColor blackColor];
    //提交动画
    [UIView commitAnimations];
//    [UIView animateWithDuration:2 animations:^{
//        btn.frame=CGRectMake(80, 30, 50, 50);
//        btn.backgroundColor=[UIColor blackColor];
//    }];
}
-(void)viewstop
{
    NSLog(@"viewstop");
}
-(void)viewstart
{
    NSLog(@"viewstart");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

注意事项:在动画中不能通过btn.frame.origin.x来改变,需要给btn.frame重新赋值