自定义交互式UIViewController转换

时间:2015-08-02 04:14:59

标签: ios objective-c iphone animation uiviewcontroller

我想实现一个自定义交互式UIViewController转换,其工作方式如下:

  • 有一个父UIViewController,它呈现一个全屏子UIViewController。
  • 如果向左滑动,子视图控制器将向左移动,右侧会出现一个新的子视图控制器。
  • 如果转换完成,则新的子视图控制器将占用屏幕并删除旧的子视图控制器。

交互必须是交互式的,以便过渡动画与滑动手势一起发生。

我想到了两种实现方法:

1)使用UINavigationController并实现UINavigationControllerDelegate协议,在那里设置动画和交互控制器。

但是,这不是一个好的解决方案,因为我不想要基于堆栈的导航,也不想保留对旧的子视图控制器的引用。

2)实现UIViewControllerTransitioningDelegate协议并使用“presentViewController:animated:completion:”方法。

但是,此方法应该用于以模态方式呈现视图控制器,而不是用新的视图控制器替换当前显示的视图控制器。

有不同的方法吗?

1 个答案:

答案 0 :(得分:0)

您不必拥有多个UIViewControllers来接触您的目标,也不建议这样做,并且它会给您带来很多内存问题。

最佳做法是拥有一个UIViewController,并向用户显示滑动效果,并在同一时间更改视图的数据。

此代码将提供很酷的滑动效果:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UISwipeGestureRecognizer *recognizerRight;
    recognizerRight.delegate = self;

    recognizerRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRight:)];
    [recognizerRight setDirection:UISwipeGestureRecognizerDirectionRight];
    [self.view addGestureRecognizer:recognizerRight];


    UISwipeGestureRecognizer *recognizerLeft;
    recognizerLeft.delegate = self;
    recognizerLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeleft:)];
    [recognizerLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
    [self.view addGestureRecognizer:recognizerLeft];
}

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

-(void)swipeleft:(UISwipeGestureRecognizer *)swipeGesture
{
    CATransition *animation = [CATransition animation];
    [animation setDelegate:self];
    [animation setType:kCATransitionPush];
    [animation setSubtype:kCATransitionFromRight];
    [animation setDuration:0.50];
    [animation setTimingFunction:
     [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [self.view.layer addAnimation:animation forKey:kCATransition];

    [self changeViewContent];
}

-(void)swipeRight:(UISwipeGestureRecognizer *)swipeGesture
{
    CATransition *animation = [CATransition animation];
    [animation setDelegate:self];
    [animation setType:kCATransitionPush];
    [animation setSubtype:kCATransitionFromLeft];
    [animation setDuration:0.40];
    [animation setTimingFunction:
     [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [self.view.layer addAnimation:animation forKey:kCATransition];

    [self changeViewContent];
}

-(void)changeViewContent
{
    // change the view content here
}

此外,如果要在它们之间交换的视图具有完全不同的UI,则可以使用UITableViewController并在每次滑动时更改表格单元格以获得所需的输出。

我希望能帮到你。