一点两个uiview动画切换的体会

糜单弓
2023-12-01

最近看了一点ios动画的东西,那天写了一个简单的demo,是关于两个view切换的动画,但是写完之后发现执行出来居然是整个view的切换。后面查了下资料,发现两个view的切换需要一个view做为容器。现在我分别用

transitionWithView:duration:options:animations:completion:和transitionFromView:toView:duration:options:completion:两个方法分别实现一个两个view动画的切换。。

 

创建一个containview  还有个两个作为切换的视图。

 

@interface ViewController ()

@property(nonatomic,strong) UIView *containview;
@property(nonatomic,strong)  UIView *view1;
@property(nonatomic,strong)  UIView *view2;
@property(nonatomic,assign)  BOOL  isview1;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _containview=[[UIView alloc]initWithFrame:CGRectMake(100, 100, 100, 200)];
    //你可以把父视图的size放大点,可以看到切换是以父视图作为切换的
  //  _containview.backgroundColor=[UIColor redColor];
    [self.view addSubview:_containview];// 创建一个容器,做为要切换的两个view的父视图
    //frame的一定要设为point一定要设为(0,0)因为是frame相对于父试图的坐标
    _view1=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 200)];
    
    _view1.backgroundColor=[UIColor grayColor];
    [_containview addSubview:_view1];
    _isview1=YES;//把当前视图设为view1
    
    _view2=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 200)];
    _view2.backgroundColor=[UIColor blueColor];
   

    
    // Do any additional setup after loading the view, typically from a nib.
}

 

 

 

然后就是试图的切换了 我们先使用transitionWithView:duration:options:animations:completion:方法

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if(_isview1==YES)
    {
    [UIView transitionWithView:_containview duration:1 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{     //options指定了过渡的方法,你可以自己指定具体的方式,具体的过渡效果可以参考apple的文档
        [_view1 removeFromSuperview];
        [_containview addSubview:_view2];
    
        
       }completion:^(BOOL finished){
           _isview1=NO;
        
       }];
    }
    else
    {
       [ UIView transitionWithView:_containview duration:1 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
            [_view2 removeFromSuperview];
            [_containview addSubview:_view1];
            
        }completion:^(BOOL finished) {
            _isview1=YES;
        
        }];
    }
}

 


再来看下transitionFromView:toView:duration:options:completion:方法

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if(_isview1==YES)
    {
    [UIView transitionFromView:_view1 toView:_view2 duration:1 options:UIViewAnimationOptionTransitionFlipFromLeft completion:^(BOOL finished) {
        _isview1=NO;
    }];//这个方法相当于系统执行了上面的 [_view1 removeFromSuperview];[_containview addSubview:_view2];
        
    }
    else
    {
        [UIView transitionFromView:_view2 toView:_view1 duration:1 options:UIViewAnimationOptionTransitionFlipFromLeft completion:^(BOOL finished) {
            _isview1=YES;
        }];
    }
}

 

转载于:https://www.cnblogs.com/xiaomingtongxue/p/4456738.html

 类似资料: