Search code examples
swift3uicollectionview

how to switch from collection view(grid view) to table view(list view) using a button?


In this already I had implemented the collection view needs to invalidate the layout and need to implement the table view(list view) when i select a button the image is as shown below

image

Can anyone tell me how to implement this in swift 3?

This image

This image mentioned is already implemented in code now I need to change to as mentioned in above image.


Solution

  • Try this

    import UIKit 
          class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource ,UICollectionViewDelegate,UICollectionViewDataSource{
    
    
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var collectionView: UICollectionView!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.alpha = 0
        collectionView.alpha = 1
           
    

    }

    @IBAction func Button1(_ sender: Any) {
        
        tableView.alpha = 0
        collectionView.alpha = 1
    }
    
    @IBAction func Button2(_ sender: Any) {
        
        tableView.alpha = 1
        collectionView.alpha = 0
    
    }
    // Table View
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
        
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        
        return 4
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
        cell.lblName.text = "dd "
        cell.lblreview.text = " fff"
        return cell
    }
    //Collection View
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
        
        
        return cell
    }