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.
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With