CollectionView切換Layout動畫處理

很多時候我們需要列表和宮格視圖的來回切換,就像蘋果的天氣應(yīng)用一樣,我之前見過一個用tableview和collectionview來實現(xiàn)這種效果的,我本人不太喜歡這個,那么有沒有更好的方法呢?答案是:有

初識UICollectionView

UICollectionView是一個比UITableView更靈活強(qiáng)大的控件。其他怎么使用這個控件這里不講述,這里只說列表和宮格的切換。我們查看UICollectionView的API,可以發(fā)現(xiàn)有這么一個方法:

open func setCollectionViewLayout(_ layout: UICollectionViewLayout, animated: Bool) // transition from one layout to another

他的解釋是轉(zhuǎn)換一個布局到另一個布局。這不就是我們想要的嘛,我們實現(xiàn)兩個布局,通過該方法,來回切換布局就行了。

接下來我們通過代碼來實現(xiàn)

我們創(chuàng)建一個工程,命名為ListAndGrid,我們直接在默認(rèn)創(chuàng)建的ViewController中先寫這么幾個屬性

var collectionView: UICollectionView!
var datas: [String] {
        var d = [String]()
        for i in 1...100 {
            d.append("\(i)")
        }
        return d
    }
 let listLayout = UICollectionViewFlowLayout() // 列表布局
 let gridLayout = UICollectionViewFlowLayout() // 宮格布局

接下來我們在viewDidLoad方法中對這幾個屬性進(jìn)行初始設(shè)置

代碼如下

override func viewDidLoad() {
        super.viewDidLoad()
        
        listLayout.itemSize = CGSize(width: UIScreen.main.bounds.size.width, height: 100)
        
        gridLayout.itemSize = CGSize(width: (UIScreen.main.bounds.size.width - 4) / 3.0, height: 50)
        gridLayout.minimumLineSpacing = 2
        gridLayout.minimumInteritemSpacing = 2
        
        collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: listLayout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(UINib.init(nibName: "LabelCell", bundle: nil), forCellWithReuseIdentifier: "LabelCell")

        collectionView.backgroundColor = UIColor.white
        view.addSubview(collectionView)
        // Do any additional setup after loading the view, typically from a nib.

 }

然后實現(xiàn)UICollectionView相應(yīng)的代理方法

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return datas.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
       let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LabelCell", for: indexPath) as! LabelCell
       cell.label.text = datas[indexPath.row]
       return cell
}

至此我們已經(jīng)實現(xiàn)所有基本代碼,接下來我們需要觸發(fā)setCollectionViewLayout這個方法,我這里是在導(dǎo)航控制器上添加了一個item,這里給出觸發(fā)事件的代碼

@IBAction func clickItem(_ sender: UIBarButtonItem) {
        if collectionView.collectionViewLayout == listLayout {
            collectionView.setCollectionViewLayout(gridLayout, animated: true)
        } else {
           collectionView.setCollectionViewLayout(listLayout, animated: true)
        }
}

運(yùn)行程序,效果如下圖

切換之后改變cell樣式

這是cell樣式一樣的情況,如果我們要在不用的布局中用不同的cell樣式該怎么辦呢?

我們首先要在viewDidLoad中添加另一個cell的注冊代碼,以便復(fù)用

collectionView.register(UINib.init(nibName: "LabelCell2", bundle: nil), forCellWithReuseIdentifier: "LabelCell2")

然后func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell代理中也需要做一些改變,我們需要區(qū)分是哪種布局,改為下面這樣

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if collectionView.collectionViewLayout == listLayout {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LabelCell", for: indexPath) as! LabelCell
            cell.label.text = datas[indexPath.row]
            return cell
        } else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LabelCell2", for: indexPath) as! LabelCell2
            cell.label.text = datas[indexPath.row]
            return cell
        }
}

最后關(guān)鍵的地方來了,我們?nèi)绻弥暗那袚Q布局方法會發(fā)現(xiàn)根本達(dá)不到目的,我們查看API發(fā)現(xiàn)有一個類似的方法是:func setCollectionViewLayout(_ layout: UICollectionViewLayout, animated: Bool, completion: ((Bool) -> Swift.Void)? = nil),這個方法比之前那個多一個完成之后的回調(diào),我們可以利用回調(diào)來重新加載一下數(shù)據(jù)就可以了,這次觸發(fā)時間里的代碼如下:

@IBAction func clickItem(_ sender: UIBarButtonItem) {
        if collectionView.collectionViewLayout == listLayout {
            collectionView.setCollectionViewLayout(gridLayout, animated: true, completion: { (com) in
                    if com {
                        self.collectionView.reloadData()
                    }
            })
            
        } else {
            collectionView.setCollectionViewLayout(listLayout, animated: true, completion: { (com) in
                    if com {
                        self.collectionView.reloadData()
                    }
            })
            
        }
}

我們是在布局切換完之后又重新刷了一下數(shù)據(jù)。

運(yùn)行程序,效果如下


至此,基本的內(nèi)容已經(jīng)講解完,通過這些我們可以完成更復(fù)雜的內(nèi)容。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容