博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【swift3.0】- 创建CollectionView方式的细节问题
阅读量:7030 次
发布时间:2019-06-28

本文共 8858 字,大约阅读时间需要 29 分钟。

  hot3.png

贡献作者 -【XJDomain】

博客XJ: 
GitHub

1:方式1: 在一个控制器中通过代码来创建collectionview,代码如下,实现数据源和代理方法太简单不写了

fileprivate lazy var collectionView : UICollectionView = { [unowned self] in        let layout = UICollectionViewFlowLayout()        layout.itemSize = CGSize(width: kItemW, height: kItemW + 50)        layout.minimumLineSpacing = klineMargin        layout.minimumInteritemSpacing = 0        layout.sectionInset = UIEdgeInsetsMake(30, kMiddleMargin, 30, kMiddleMargin)                let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)        collectionView.dataSource = self        collectionView.delegate = self        collectionView.showsVerticalScrollIndicator = false        collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]        collectionView.backgroundColor = kColorGrayBg        collectionView.alwaysBounceVertical = true        collectionView.register(UINib(nibName: "CHCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: kCollectionCellID)        return collectionView        }()

 

2:方式2: 在一个控制器中通过xib来创建collectionview

基本步骤:

01-创建一个控制器,同时创建一个xib

02-在xib中添加一个collectionView,添加约束以后就完成了

03-在控制器中拖入collectionView属性,同时在xib中右键拖入dataSource连线给控制器,成为数据源代理

04-在控制器中实现数据源和代理的相关方法即可

 

3:方式3:在一个view上通过xib添加来创建一个collectionView

基本步骤和上面基本步骤差不多,只是连线的时候是连接给父view,而不是控制器

注意点是:修改布局约束,有两种方式:

方式1:layoutSubviews()中去实现约束

override func layoutSubviews() {        super.layoutSubviews()                let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout        layout.itemSize = collectionView.bounds.size        layout.minimumLineSpacing = 0        layout.minimumInteritemSpacing = 0        layout.scrollDirection = .horizontal        collectionView.isPagingEnabled = true        collectionView.backgroundColor = UIColor.white        collectionView.showsHorizontalScrollIndicator = false    }

 

方式2: 写一个类继承自UICollectionViewFlowLayout,

01-实现prepare方法,然后调用super.prepare

02-书写item约束即可

 

 

////  XJAmuseMenuView.swift//  XJZB////  Created by 李胜兵 on 16/10/17.//  Copyright © 2016年 付公司. All rights reserved.//import UIKitprivate let kCellID = "kCellID"class XJAmuseMenuView: UIView {            // MARK: - 设置属性    var groups : [XJAnchorGroup]? {        didSet {            collectionView.reloadData()        }    }            // MARK: - 控件属性    @IBOutlet weak var collectionView: UICollectionView!    @IBOutlet weak var pageControl: UIPageControl!        // MARK: - 系统回调函数    override func awakeFromNib() {        super.awakeFromNib()        autoresizingMask = UIViewAutoresizing()                // 注册cell        collectionView.register(UINib(nibName: "XJAmuseMenuCollectionVIewCell", bundle: nil), forCellWithReuseIdentifier: kCellID)            }        override func layoutSubviews() {        super.layoutSubviews()                let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout        layout.itemSize = collectionView.bounds.size        layout.minimumLineSpacing = 0        layout.minimumInteritemSpacing = 0        layout.scrollDirection = .horizontal        collectionView.isPagingEnabled = true        collectionView.backgroundColor = UIColor.white        collectionView.showsHorizontalScrollIndicator = false    }        }extension XJAmuseMenuView {    class func menuView() -> XJAmuseMenuView {        return Bundle.main.loadNibNamed("XJAmuseMenuView", owner: nil, options: nil)?.first as! XJAmuseMenuView    }}extension XJAmuseMenuView : UICollectionViewDataSource {    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {        if groups == nil { return 0 }        let pageNum = (groups!.count - 1 ) / 8 + 1        pageControl.numberOfPages = pageNum        return pageNum    }        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "kCellID", for: indexPath) as! XJAmuseMenuCollectionVIewCell        // 给cell设置数据        setupCellDataWithCell(cell: cell, indexPath: indexPath)        return cell    }            private func setupCellDataWithCell(cell : XJAmuseMenuCollectionVIewCell, indexPath : IndexPath) {        // 0页: 0 ~ 7        // 1页: 8 ~ 15        // 2页: 16 ~ 23        // 1.取出起始位置 && 终点位置        let starIndex = indexPath.item * 8        var endIndex = (indexPath.item + 1) * 8 - 1                // 2.判断越界问题        if endIndex > groups!.count - 1 {            endIndex = groups!.count - 1        }                // 3.取出数据,并且赋值给cell        cell.groups = Array(groups![starIndex...endIndex])    }        }extension XJAmuseMenuView : UICollectionViewDelegate {    func scrollViewDidScroll(_ scrollView: UIScrollView) {        pageControl.currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.width)    }}

 

 

4:方式4:在一个view上通过xib添加来创建一个collectionView,但是是让自己成为自己的代理

步骤同3差不多,只是不用拖线,但是需要自己自定义一个collectionView,如:

然后再创建一个xib对应其中的自定义cell,然后在cell中添加其他控件就可以了

////  XJPicImageCollectionView.swift//  XJWeiBo////  Created by 李胜兵 on 16/10/27.//  Copyright © 2016年 李胜兵. All rights reserved.//import UIKitimport Kingfisherprivate let cellIdentifier = "cellIdentifier"class XJPicImageCollectionView: UICollectionView {        // MARK: - 定义属性    var picUrls : [URL] = [URL]() {        didSet {            reloadData()        }    }    // MARK: - 系统回调函数    override func awakeFromNib() {        super.awakeFromNib()        // 设置数据源        dataSource = self        delegate = self        isScrollEnabled = false        register(UINib(nibName: "XJPicImageCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: cellIdentifier)    }}extension XJPicImageCollectionView : UICollectionViewDataSource, UICollectionViewDelegate {    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {        return picUrls.count    }        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! XJPicImageCollectionViewCell        cell.iconView.kf.setImage(with: picUrls[indexPath.item], placeholder: UIImage(named: "empty_picture"))        return cell    }        func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {        print("--------")    }}// MARK: - 自定义cell类class XJPicImageCollectionViewCell: UICollectionViewCell {        // MARK: - 系统属性    @IBOutlet weak var iconView: UIImageView!    override func awakeFromNib() {        super.awakeFromNib()            }    }

 

范例2:

////  XJRecommendGameView.swift//  XJZB////  Created by 李胜兵 on 16/10/12.//  Copyright © 2016年 付公司. All rights reserved.//import UIKitprivate let kGameCellID = "kGameCellID"private let kEdgeInsetMargin : CGFloat = 10class XJRecommendGameView: UIView {        // MARK: - 定义数据的属性    var groups : [XJBaseModel]? {        didSet {            // 刷新数据            collectionView.reloadData()        }    }                // MARK: - 控件属性    @IBOutlet weak var collectionView: UICollectionView!        // 系统回调函数    override func awakeFromNib() {        super.awakeFromNib()                // 让控件不随着父控件的拉伸而拉伸        autoresizingMask = UIViewAutoresizing()                // 注册cell        collectionView.register(UINib(nibName: "XJGameCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID)                // 给collectionView添加内边距        collectionView.contentInset = UIEdgeInsetsMake(0, kEdgeInsetMargin, 0, kEdgeInsetMargin)    }        override func layoutSubviews() {        super.layoutSubviews()                let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout        layout.itemSize = CGSize(width: 80, height: collectionView.bounds.size.height)        layout.minimumLineSpacing = 0        layout.minimumInteritemSpacing = 0        layout.scrollDirection = .horizontal        collectionView.showsHorizontalScrollIndicator = false    }}// MARK: - 快速创建的类方法extension XJRecommendGameView {    class func recommendGameView() -> XJRecommendGameView {        return Bundle.main.loadNibNamed("XJRecommendGameView", owner: nil, options: nil)?.first as! XJRecommendGameView    }}// MARK: - collectionView数据源extension XJRecommendGameView : UICollectionViewDataSource {    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {        return groups?.count ?? 0    }        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! XJGameCollectionViewCell        cell.group = groups![(indexPath as NSIndexPath).item]        return cell    }}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

转载于:https://my.oschina.net/shengbingli/blog/792154

你可能感兴趣的文章
javascript继承方法以及优缺点
查看>>
tab 切换下划线跟随实现
查看>>
20+个很棒的Android开源项目
查看>>
跨域、vue双向绑定相关面试题
查看>>
Web Components(一)入门
查看>>
mpvue打包没有app.json等配置文件的解决方法
查看>>
树莓派配置swoole环境
查看>>
JavaScript 工作原理之十二-网络层探秘及如何提高其性能和安全性
查看>>
搭建基于react项目的心得
查看>>
react-native踩坑记录
查看>>
HTTP API 设计入坑指南(一)
查看>>
OkHttp源码分析
查看>>
【挖坑系列】跨域问题相关
查看>>
使用cronolog切割nginx访问日志,定时清理旧日志
查看>>
PHP最常用函数TOP100(翻译)
查看>>
大数据科学新发展展望:不得不知的四大趋势
查看>>
python多线程、锁、event事件机制的简单使用
查看>>
ES6系列之解构赋值
查看>>
goLang 文件操作之二
查看>>
7大维度看国外企业为啥选择gRPC打造高性能微服务?
查看>>