Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch UITableView and UICollectionView

I have a project with a button that allows the user to switch between list view (UITableView) and grid view (UICollectionView) but I don't know how to do it.

like image 302
Brian Nguyen Avatar asked Jan 03 '13 12:01

Brian Nguyen


1 Answers

Let's suppose that your controller has a UITableView property named tableView and a UICollectionView property named collectionView. In your viewDidLoad you need to add the starting view. Let's suppose it's the table view:

- (void)viewDidLoad
{
    self.tableView.frame = self.view.bounds;
    [self.view addSubview:self.tableView];
}

Then in your button callback, swap the views out:

- (void)buttonTapped:(id)sender
{
     UIView *fromView, *toView;

     if (self.tableView.superview == self.view)
     {
         fromView = self.tableView;
         toView = self.collectionView;
     }
     else
     {
         fromView = self.collectionView;
         toView = self.tableView;
     }

     [fromView removeFromSuperview];

     toView.frame = self.view.bounds;
     [self.view addSubview:toView];
}

If you want a fancy animation, you can use +[UIView transitionFromView:toView:duration:options:completion:] instead:

- (void)buttonTapped:(id)sender
{
     UIView *fromView, *toView;

     if (self.tableView.superview == self.view)
     {
         fromView = self.tableView;
         toView = self.collectionView;
     }
     else
     {
         fromView = self.collectionView;
         toView = self.tableView;
     }

     toView.frame = self.view.bounds;
     [UIView transitionFromView:fromView
                         toView:toView
                       duration:0.25
                        options:UIViewAnimationTransitionFlipFromRight
                     completion:nil];
}
like image 108
Simon Avatar answered Sep 20 '22 15:09

Simon