美文网首页
CollectionView-基础布局

CollectionView-基础布局

作者: 小凡凡520 | 来源:发表于2019-02-21 16:19 被阅读3次
    一、简介

    我们日常开发中大部分的列表视图都可以使用 UITableView 完美的实现,它使用起来非常的简单高效。但是面对一些网格视图和瀑布流,甚至交叉布局,圆形等各种创新布局,UITableView 显得束手无策,这时候我们需要祭出 UICollectionView ,它真的是一个非常强大的控件, 既可以实现简单的列表网格等布局,也可以完成各种复杂的自定义布局,以及动画特效。是一个非常值得花时间去学习的控件。所以我打算对此做一个总结,从基础的FlowLayout 到各种 自定义布局。全面的学习这个控件。

    二、说明

    UICollectionView 的基本使用非常简单,和UITableView类似。但是它将展示和布局分开处理。UICollectionView 负责展示数据,UICollectionViewLayout 负责处理布局信息,系统默认帮我们实现了一种流式布局 UICollectionViewFlowLayout ,可以满足大部分场景。下面展示简单的例子。

    三、案例
    import UIKit
    
    class ViewController: UIViewController {
    
        @IBOutlet weak var collectionView: UICollectionView!
        
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
            
            collectionView.delegate = self
            collectionView.dataSource = self
            
            let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout
            // 元素大小
            let row:CGFloat = 4
            let space:CGFloat = 5
            layout?.itemSize = CGSize(width: (UIScreen.main.bounds.size.width - (row - 1) * space) / row, height: (UIScreen.main.bounds.size.width - (row - 1) * space) / row)
            // 元素行垂直间距
            layout?.minimumLineSpacing = space
            // 元素水平间距
            layout?.minimumInteritemSpacing = 0
        }
    }
    
    extension ViewController:UICollectionViewDelegate {
        
        
    }
    extension ViewController:UICollectionViewDataSource {
        
        func numberOfSections(in collectionView: UICollectionView) -> Int {
            return 20
        }
        
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return 19
        }
        
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "id", for: indexPath)
            let r = Double(arc4random() % 255)
            let g = Double(arc4random() % 255)
            let b = Double(arc4random() % 255)
            cell.backgroundColor = UIColor(red: CGFloat(r / 255.0), green: CGFloat(g / 255.0), blue: CGFloat(b / 255.0), alpha: 1)
            return cell
        }
    }
    

    相关文章

      网友评论

          本文标题:CollectionView-基础布局

          本文链接:https://www.haomeiwen.com/subject/rpnryqtx.html