Swift之UICollectionView

UICollectionView可以说是一个比较常用的控件了,在用Swift写的过程中还是遇到了一些问题的,记下来方便下次的使用。
首先在xib中创建一个collectionView,命名为 myCollectionView
创建全局变量let flowLayout = UICollectionViewFlowLayout()
viewDidLoad()中进行添加代理等操作

override func viewDidLoad() {
        super.viewDidLoad()       
        myCollectionView.delegate = self
        myCollectionView.dataSource = self
        initViews()
}

func initViews() {
        //  屏幕宽高
        var KSCREEN_HEIGHT =  UIScreen.mainScreen().bounds.size.height
        var KSCREEN_WIDTH =  UIScreen.mainScreen().bounds.size.width
        //  collectionviewcell 复用标识
        private let cellIdentifier = "myCell"
        // 竖屏时每行显示4张图片
        let shape: CGFloat = 5
        let cellWidth: CGFloat = (KSCREEN_WIDTH - 5 * shape) / 4
        flowLayout.sectionInset = UIEdgeInsetsMake(0, shape, 0, shape)
        flowLayout.itemSize = CGSizeMake(cellWidth, cellWidth / 2 * 3)
        flowLayout.minimumLineSpacing = shape
        flowLayout.minimumInteritemSpacing = shape
        flowLayout.footerReferenceSize = CGSizeMake(KSCREEN_WIDTH, 40)
        myCollectionView.setCollectionViewLayout(flowLayout, animated: true)
        
        //注册cell
        let cellNib = UINib(nibName: "myCollectionViewCell",bundle: nil)
        myCollectionView.registerNib(cellNib, forCellWithReuseIdentifier: cellIdentifier)
        
    }

接下来就是常用到的实现代理方法

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell:myCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! myCollectionViewCell
        // 填入相应的数据
        return cell
    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //点击cell的方法
    }

项目中遇到的需求进入页面整个页面要拉到最下面,使用setContentOffset方法即可,不过一开始总是进入页面后没有反应,经过多次实验,并参考网上的答案,写在viewDidAppear方法中成功了。不过这样的话页面会在进入后在自动下拉到最下方,我是暂时用一个0.5秒到刷新动画来盖住了页面的动画,具体以后想到更好的解决办法在来更新。

    override func viewDidAppear(animated: Bool) {
        myCollectionView.setContentOffset(CGPointMake(0, myCollectionView.contentSize.height - myCollectionView.frame.size.height), animated: false)
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容