美文网首页Swiftios-tipsiOS 控件定制
Swift 使用CollectionView 实现图片轮播封装

Swift 使用CollectionView 实现图片轮播封装

作者: 夏天然后 | 来源:发表于2016-04-28 22:13 被阅读3795次

    前言: 这篇你可以学会自定义视图,创建collectionView,协议的使用,定时器;

    自制图片
    先上Demo:Github上封装好的下载即用, 好用请Star Thanks
    首先新建一个继承于UIView的视图, 且用collectionView实现所以需要签订两个协议代码如下:
    let sectionNum: Int = 100 // 区的数量
    let width =  UIScreen.mainScreen().bounds.size.width // 屏幕宽度
    let height = UIScreen.mainScreen().bounds.size.width // 屏幕高度 
    // 因为要实现轮播图片可以点击定义一个协议
    // 协议
    protocol XTCycleViewDelegate {
        func didSelectIndexCollectionViewCell(index: Int)->Void
    }
    
    class XTCycleScrollView: UIView, UICollectionViewDelegate, UICollectionViewDataSource{
    
    

    使用到的变量以及创建视图

        var delegate: XTCycleViewDelegate?
        var cycleCollectionView: UICollectionView?
        var images = NSMutableArray()
        var pageControl = UIPageControl()
        var flowlayout = UICollectionViewFlowLayout()
        var timer = NSTimer()
        override init(frame: CGRect) {
            super.init(frame: frame)
            self.createSubviews(frame)
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    

    布局必要的UI以及创建定时器

        func createSubviews(frame: CGRect){
            cycleCollectionView = UICollectionView.init(frame: CGRectMake(0, 0, frame.size.width, frame.size.height), collectionViewLayout: flowlayout)
            flowlayout.itemSize = CGSizeMake(frame.size.width, frame.size.height);
            flowlayout.minimumInteritemSpacing = 0;
            flowlayout.minimumLineSpacing = 0;
            flowlayout.scrollDirection = UICollectionViewScrollDirection.Horizontal;
            cycleCollectionView!.backgroundColor = UIColor.lightGrayColor()
            cycleCollectionView!.pagingEnabled = true
            cycleCollectionView!.dataSource  = self
            cycleCollectionView!.delegate = self
            cycleCollectionView!.showsHorizontalScrollIndicator = false
            cycleCollectionView!.showsVerticalScrollIndicator = false
            cycleCollectionView!.registerClass(ZJCustomCycleCell.self, forCellWithReuseIdentifier: "cellId")
            self.addSubview(cycleCollectionView!)
            pageControl = UIPageControl.init(frame: CGRectMake(0, 0, frame.size.width / 2, 30))
            pageControl.center = CGPointMake(frame.size.width / 2, frame.size.height - 20);
            self.addSubview(pageControl);
            self.addTimer()
        }
    

    定时器初始化

    func addTimer(){
            let timer1 = NSTimer.init(timeInterval: 2, target: self, selector: "nextPageView", userInfo: nil, repeats: true)
            NSRunLoop.currentRunLoop().addTimer(timer1, forMode: NSRunLoopCommonModes)
            timer = timer1
        }
    

    销毁定时器

    func removeTimer(){
            self.timer.invalidate()
        }
    

    实现循环滚动

     func returnIndexPath()->NSIndexPath{
            var currentIndexPath = cycleCollectionView!.indexPathsForVisibleItems().last
            currentIndexPath = NSIndexPath.init(forRow: (currentIndexPath?.row)!, inSection: sectionNum / 2)
            cycleCollectionView!.scrollToItemAtIndexPath(currentIndexPath!, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
            return currentIndexPath!;
        }
     func nextPageView(){
    
            let indexPath = self.returnIndexPath()
            var item = indexPath.row + 1;
            var section = indexPath.section;
            if item == images.count {
                item = 0
                section++
            }
            self.pageControl.currentPage = item;
            let nextIndexPath = NSIndexPath.init(forRow: item, inSection: section)
            cycleCollectionView!.scrollToItemAtIndexPath(nextIndexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
        }
    

    collectionView Delegate

         // 重用池
         func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
            // 这里使用的自定义cell, 下面会贴出自定义cell代码
            let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cellId", forIndexPath: indexPath) as! ZJCustomCycleCell
            // 这个Label实现显示数字,表示是第几张图片
            cell.labelTitle.text = NSString(format: "%d", indexPath.row) as String
            // 这里是图片赋值
            let url:String = self.images[indexPath.row] as! String
            // 这里我使用的是一个赋值图片的三方库,看自己喜好,为方便我没有自己写
            cell.imageView.hnk_setImageFromURL(NSURL.init(string: url)!)
            return cell
        }
        func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
            return sectionNum
        }
        func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            // 在这里给出了pageControl的数量
            pageControl.numberOfPages = images.count
            return images.count
        }
    
        //  重新添加定时器
        func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
            self.addTimer()
        }
        // 手动滑动的时候销毁定时器
        func scrollViewWillBeginDragging(scrollView: UIScrollView) {
            self.removeTimer()
        }
    

    设置当前的pagecontrol

    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
            let page = (Int(scrollView.contentOffset.x) / Int(width)) % images.count
            pageControl.currentPage = page
        }
    

    点击方法

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
            self.delegate?.didSelectIndexCollectionViewCell(indexPath.row)
        }
    

    下面是我在自定义cell中的代码

        var urlImage: String = ""
        var imageView = UIImageView()
        var labelTitle = UILabel()
        override init(frame: CGRect) {
            super.init(frame: frame)
            self.createSubviews(frame)
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        func createSubviews(frame: CGRect){
            imageView = UIImageView.init(frame: CGRectMake(0, 0, frame.size.width, frame.size.height))
            self.contentView.addSubview(imageView)
            labelTitle = UILabel.init(frame: CGRectMake(10, 10, 30, 30))
            imageView.addSubview(labelTitle)
        }
    

    封装基本完成了, 下面看看如何使用

            // 创建
            let cycle = XTCycleScrollView.init(frame: CGRectMake(0, 70, width, 175))
            // 要实现点击需要制定代理人
            cycle.delegate = self;
            // 图片链接数组
            let images: NSMutableArray = ["", "", "", ""]
            // 数组赋值
            cycle.images = images
            self.view.addSubview(cycle)
    

    实现代理方法

    func didSelectIndexCollectionViewCell(index: Int) {
            print("\\(index)")
        }
    

    走心文章, 值得点赞 ---文/夏天然后
    微博@夏天是个大人了 QQQ: 498143780

    转载获得授权

    相关文章

      网友评论

      • 林江漓:照着你贴的代码敲了一遍,果然一遍就成功 :+1:
        林江漓:好啦好啦,再夸你一遍66666666666
        夏天然后:@林江漓 :unamused:我会贴实现不了的代码吗:smiley:
      • 改个假名稳当点:图片是代码的实现效果吗?
        夏天然后:@改个假名稳当点 3-123-1
        改个假名稳当点:@Xt的风 如果用scrollview实现轮播图,假如是3张图片,你会怎么实现效果呢?是放4张图轮播吗,1-2-3-1?
        夏天然后:@改个假名稳当点 当然、在图片数组中放入图片链接就可以了、我把链接删除了:smile:

      本文标题:Swift 使用CollectionView 实现图片轮播封装

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