2013-01-03 51 views
11

我有一個按鈕,允許用戶在列表視圖(UITableView)和網格視圖(UICollectionView)之間切換,但我不知道該怎麼做。如何切換UITableView和UICollectionView

+6

這不是很差的英語,但它目前是一個很差的問題。你堅持什麼_exactly_?到目前爲止你想做什麼? –

+0

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

回答

19

假設您的控制器具有名爲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

2

解決這個問題的另一種方法是使用單個UICollectionView,您可以在其中根據所需模式切換UICollectionViewFlowLayout實施。

爲了轉換從UITableViewUICollectionView,也有很多的教程在網上,例如this

相關問題