美文网首页
Swift 3 - 创建collectionView(系统流水布

Swift 3 - 创建collectionView(系统流水布

作者: 壹点微尘 | 来源:发表于2017-04-16 11:33 被阅读94次
    import UIKit
    
    private let CollectionCellId = "CollectionCell"
    
    class ViewController: UIViewController {
    
        //懒加载 collectionView
        fileprivate lazy var collectionView : UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout())
        
        override func viewDidLoad() {
            super.viewDidLoad()
    
            view.addSubview(collectionView)
            collectionView.frame = view.bounds
            collectionView.backgroundColor = UIColor(red: 244/255.0, green: 244/255.0, blue: 244/255.0, alpha: 1)
            collectionView.dataSource = self;
            collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: CollectionCellId) //注册cell
            
            //设置流水布局 layout
            let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
            layout.itemSize = CGSize(width: 120 , height: 120)
            layout.minimumLineSpacing = 2  //行间距
            layout.minimumInteritemSpacing = 2  //列间距
            layout.scrollDirection = .horizontal //滚动方向
            
            collectionView.isPagingEnabled = true  //设置分页效果
            collectionView.showsHorizontalScrollIndicator = false  //隐藏水平滚动条
            
    
        }
    
    
    }
    
    //MARK:- UICollectionViewDataSource
    extension ViewController : UICollectionViewDataSource{
        
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return 100;
        }
       
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionCellId, for: indexPath)
            
            let R = (arc4random() % 256)
            let G = (arc4random() % 256)
            let B = (arc4random() % 256)
            
            cell.backgroundColor = UIColor(red: CGFloat(R)/255, green: CGFloat(G)/255, blue: CGFloat(B)/255, alpha: 1.0)
            
            return cell
            
            
        }
        
        
        
        
    }
    
    
    
    效果图.png

    相关文章

      网友评论

          本文标题:Swift 3 - 创建collectionView(系统流水布

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