Swift轮播图

最近在学习swift,就用swift实现轮播图来练习一下

轮播图的创建有两种方式:
    1>可以用scrollview创建3个view,自己实现循环利用
    2>利用collectionView由系统来处理item的循环利用问题

显然使用collectionView实现的方式比较简单。

轮播图由两部分组成,collectionView和一个pageControl。自定义一个CarouselView,懒加载创建collectionView和pageControl:

fileprivate lazy var carouselCollectionView : UICollectionView = { [unowned self] in
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = UICollectionViewScrollDirection.horizontal//横向滚动
        layout.itemSize = CGSize(width: kViewWidth, height: kViewHeight)
        layout.minimumLineSpacing = 0//行间距为0
        let carouselCollectionView:UICollectionView = UICollectionView(frame: self.bounds, collectionViewLayout: layout)
        carouselCollectionView.showsHorizontalScrollIndicator = false
        carouselCollectionView.isPagingEnabled = true//按页滚动
        carouselCollectionView.backgroundColor = UIColor.white
        carouselCollectionView.register(CarouselCollectionViewCell.self, forCellWithReuseIdentifier: CellIdentifier)//注册自定义cell
        //添加代理
        carouselCollectionView.dataSource = self
        carouselCollectionView.delegate = self
        return carouselCollectionView
    }()
    
    fileprivate lazy var pageControl : UIPageControl = {
        let pageControl:UIPageControl = UIPageControl()
        pageControl.translatesAutoresizingMaskIntoConstraints = false//用代码为pageControl添加NSLayoutConstraint的时候,需要设置
        pageControl.numberOfPages = 1
        return pageControl
    }()

重写自定义视图的初始化方法

init(Y: CGFloat,H:CGFloat) {
        kViewHeight = H
        super.init(frame: CGRect(x: 0, y: Y, width: kViewWidth, height: kViewHeight))
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

使用extension为CarouselView添加一个布局方法

//MARK:- setup UI
extension CarouselView {
    func setupUI() {
        self.addSubview(carouselCollectionView)
        self.addSubview(pageControl)
        //将pageControl添加到自定义视图后,给pageControl添加约束
        let rightConstraint:NSLayoutConstraint = NSLayoutConstraint(item: pageControl, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1.0, constant: -10)
        let bottomConstraint:NSLayoutConstraint = NSLayoutConstraint(item: pageControl, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: -5)
        let heightConstraint:NSLayoutConstraint = NSLayoutConstraint(item: pageControl, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 20)
        pageControl.superview?.addConstraint(rightConstraint)
        pageControl.superview?.addConstraint(bottomConstraint)
        pageControl.superview?.addConstraint(heightConstraint)
    }
}

创建一个数组用来存储自定义CarouselModel

var carouselModelArr : [CarouselModel]? {
        didSet {
            //数组发生变化时刷新collectionView
            self.carouselCollectionView.reloadData()
            pageControl.numberOfPages = carouselModelArr?.count ?? 0
            //初识时,让collectionView滚动到中间某个位置,使用户可以向前翻页
            let index = (carouselModelArr?.count ?? 0)*10
            self.carouselCollectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .left, animated: false)
            //添加计时器
            removeTimer()
            addTimer()
        }
    }

自定义一个CarouselModel用来接收数据

class CarouselModel: NSObject {

    var title:String = ""
    var pic_url:String = ""
    
    init(dic:[String:NSObject]) {
        super.init()
        //kvc方法,字典转模型
        setValuesForKeys(dic)
    }
    //获取的数据中没定义的键值在这里处理
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
//        print("undefined key : \(key), value : \(value)")
    }
}

创建自定义cell
自定义 cell包括两部分:
1>展示图片用的imageView
2>展示文字title的Label

import UIKit
import SDWebImage

class CarouselCollectionViewCell: UICollectionViewCell {
    
    var imageView = UIImageView()
    
    var titleLabel = UILabel()
    
    var carouselModel : CarouselModel? {
        didSet {
            //设置属性时给label和imageView赋值
            titleLabel.text = carouselModel?.title
            //使用SDWebImage设置imageView图片
            imageView.sd_setImage(with: URL(string: (carouselModel?.pic_url ?? "")!), placeholderImage: UIImage(named: "placehold"))
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension CarouselCollectionViewCell {
    func setupUI() {
        imageView.frame = self.bounds
        titleLabel.frame = CGRect(x: 0, y: self.bounds.size.height - 30, width: self.bounds.size.width, height: 30)
        titleLabel.backgroundColor = UIColor(white: 0.4, alpha: 0.3)
        titleLabel.textColor = .white
        self.addSubview(imageView)
        self.addSubview(titleLabel)
    }
}

自定义CarouselView遵循 DataSource 协议

//MARK:- collectionViewDataSource
extension CarouselView : UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //返回10000倍item实现无限轮播,因为collectionView的重用机制,并不会创建这么多item,不用担心内存问题
        return 10000*(carouselModelArr?.count ?? 0);
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        //使用自定义item:CarouselCollectionViewCell
        let collectionItem = collectionView.dequeueReusableCell(withReuseIdentifier: CellIdentifier, for: indexPath) as! CarouselCollectionViewCell
        let index = indexPath.item % carouselModelArr!.count
        collectionItem.carouselModel = carouselModelArr![index]
        return collectionItem
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let item = collectionView.cellForItem(at: indexPath) as! CarouselCollectionViewCell
        print("title : \(item.titleLabel.text)")
    }
}

自定义CarouselView遵循Delegate协议

//MARK:- collectionViewDelegate
extension CarouselView : UICollectionViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //当偏移超过page的一半时pageControl调到下一个
        let offset = scrollView.contentOffset.x + kViewWidth / 2
        pageControl.currentPage = Int(offset / kViewWidth) % (carouselModelArr?.count ?? 1)
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        //用户开始拖拽时,移除定时器
        removeTimer()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        //用户停止拖拽时,打开定时器
        addTimer()
    }
}

添加计时器,使collection View滚动起来

//MARK:- 添加计时器
extension CarouselView {
    func addTimer() {
        timer = Timer(timeInterval: 3.0, target: self, selector: #selector(scrollToNextPage), userInfo: nil, repeats: true)
        RunLoop.main.add(timer!, forMode: .commonModes)
    }
    
    func removeTimer() {
        timer?.invalidate()
        timer = nil
    }
    
    func scrollToNextPage() {
        let offsetX = carouselCollectionView.contentOffset.x + kViewWidth//当前偏移量加上一页的宽度
        carouselCollectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
        
    }
}

此时,一个简单的轮播图就完成了!

下面是轮播图的使用:

import UIKit
import AFNetworking

class ViewController: UIViewController {
    //创建自定义carousView
//    let carouselView = CarouselView(Y: 64, H: 200)//需要毛玻璃效果时Y为64
    let carouselView = CarouselView(Y: 0, H: 200)//不需要毛玻璃效果时Y,为0。

    var modelArr = [CarouselModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        getArrayFromWeb()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

extension ViewController {
    func setupUI() {
//        self.automaticallyAdjustsScrollViewInsets = false//需要毛玻璃效果时设置(是否根据所在界面的navigationbar与tabbar的高度,自动调整scrollview的inset.默认是true)
        self.navigationController?.navigationBar.isTranslucent = false//不需要毛玻璃效果时设置
        self.view.addSubview(carouselView)
    }
    //使用AFN解析数据
    func getArrayFromWeb() {
        let manager = AFHTTPSessionManager()
        manager.get("http://www.douyutv.com/api/v1/slide/6", parameters: ["version" : "2.300"], progress: nil, success: { (task:URLSessionDataTask, json:Any) in
//            print("jsonData: \(json)")
            guard let dataDic = json as? [String : NSObject] else { return }
            guard let dataArr = dataDic["data"] as? [[String : NSObject]] else { return }
            for dic in dataArr {
                self.modelArr.append(CarouselModel(dic: dic))
            }
            //获取完数据,将数组赋给carouselView的carouselModelArr
            self.carouselView.carouselModelArr = self.modelArr
        }) { (task:URLSessionDataTask?, error:Error) in
            print("error : \(error)")
        }
    }
}

GitHub地址

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
禁止转载,如需转载请通过简信或评论联系作者。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容