如何切换UITableView和UICollectionView

问题描述:

我有一个按钮,允许用户在列表视图(UITableView)和网格视图(UICollectionView)之间切换,但我不知道该怎么做。如何切换UITableView和UICollectionView

+6

这不是很差的英语,但它目前是一个很差的问题。你坚持什么_exactly_?到目前为止你想做什么? –

+0

我很抱歉@但我是新手! –

假设您的控制器具有名为tableViewUITableView属性和名称为collectionViewUICollectionView属性。在您的viewDidLoad中,您需要添加开始视图。让我们假设它的表视图:

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

然后在你的按钮回调,交换意见了:

- (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]; 
} 

如果你想要一个奇特的动画,你可以使用+[UIView transitionFromView:toView:duration:options:completion:]代替:

- (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]; 
} 
+0

谢谢!但我可以使用哪个ViewController? TableViewController或CollectionViewController。我如何在外部类(不是ViewController)中使用TableViewDelegate和Datasource? –

+0

只需使用普通的UIViewController,然后将两种类型的视图添加为属性即可。或者,如果您希望将两个视图的逻辑分开,则可以创建UITableViewController和UICollectionViewController,并使用它们的视图而不是主控制器的属性。 – Simon

+0

如果您的视图已经是视图层次结构的一部分(例如通过添加xib/storyboard),您必须在'+ transitionFromView:ToView:duration:options:completion:'方法中传递'UIViewAnimationOptionShowHideTransitionViews'作为选项参数之一。 – MrBr

解决这个问题的另一种方法是使用单个UICollectionView,您可以在其中根据所需模式切换UICollectionViewFlowLayout实施。

为了转换从UITableViewUICollectionView,也有很多的教程在网上,例如this