如何切换UITableView和UICollectionView

Bri*_*yen 11 user-interface uitableview ios uicollectionview

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

Sim*_*mon 19

假设您的控制器具有UITableView名为tableViewUICollectionView属性和名为的属性collectionView.在viewDidLoad你的需要添加起始视图.我们假设它是表格视图:

- (void)viewDidLoad
{
    self.tableView.frame = self.view.bounds;
    [self.view addSubview:self.tableView];
}
Run Code Online (Sandbox Code Playgroud)

然后在按钮回调中,交换视图:

- (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];
}
Run Code Online (Sandbox Code Playgroud)

如果你想要一个花哨的动画,你可以使用+[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];
}
Run Code Online (Sandbox Code Playgroud)