• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

图片轮播器(swift)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

如何实现一个无限循环,无缝衔接的图片轮播器 自己实现一次以后就不用使用轮播器的框架了

能用代码解决的问题就不在这里瞎BB了  O(∩_∩)O

首先先在Carousel文件件夹创建以下几个文件

CarouselFlowLayout.swift

CarouselView.swift

CarouselView.xib

CarsouselCell.swift

CarsouselCell.xib

Extension.swift

//CarouselFlowLayout.swift

import UIKit

class CarouselFlowLayout: UICollectionViewFlowLayout {

override func prepare() {

super.prepare()

itemSize = collectionView?.bounds.size ?? CGSize.zero

scrollDirection = .horizontal

minimumLineSpacing = 0

minimumInteritemSpacing = 0

collectionView?.isPagingEnabled = true

collectionView?.showsVerticalScrollIndicator = false

collectionView?.showsHorizontalScrollIndicator = false

}

}

//  CarouselView.swift

//CarouselView.xib


import UIKit

private let kCellID = "CarsouselCellID"

private let kMultiple = 10000

/// 图片轮播器

public class CarouselView: UIView {

/// collectionView

@IBOutlet var collectionView: UICollectionView!

/// 页码指示器

@IBOutlet var pageControl: UIPageControl!

/// 图片地址集合

public var imageURLList: [String]? {

didSet {

collectionView.reloadData()

pageControl.numberOfPages = imageURLList?.count ?? 0

}

}

/// 定时器

var timer: Timer?

public override func awakeFromNib() {

super.awakeFromNib()

// 注册Cell

collectionView.register(UINib(nibName: "CarsouselCell", bundle: Bundle(for: CarsouselCell.self)), forCellWithReuseIdentifier: kCellID)

// 设置数据源

collectionView.dataSource = self

// 设置代理

collectionView.delegate = self

pageControl.hidesForSinglePage = true

}

public override func layoutSubviews() {

super.layoutSubviews()

collectionView.scrollToItem(at: IndexPath(item: (imageURLList?.count ?? 0) * Int(Float(kMultiple) * 0.5), section: 0), at: .left, animated: false)

}

}

// MARK: - 公共方法

extension CarouselView {

/// 获取图片轮播器

///

/// - returns: 图片轮播器对象

public static func carouselView() -> CarouselView{

return Bundle(for: CarouselView.self).loadNibNamed("CarouselView", owner: nil, options: nil)?.first as! CarouselView

}

/// 开始自动滚动

public func start() {

end()

timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(doTask), userInfo: nil, repeats: true)

RunLoop.main.add(timer!, forMode: .commonModes)

}

/// 停止自动滚动

public func end() {

timer?.invalidate()

timer = nil

}

@objc private func doTask() {

var contentOffset = collectionView.contentOffset

contentOffset.x += collectionView.frame.width

collectionView.setContentOffset(contentOffset, animated: true)

}

}

// MARK: - UICollectionViewDataSource

extension CarouselView: UICollectionViewDataSource {

public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

return (imageURLList?.count ?? 0) * kMultiple

}

public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCellID, for: indexPath) as! CarsouselCell

cell.imageURL = imageURLList?[indexPath.item % (imageURLList?.count ?? 1)]

return cell

}

}

// MARK: - UICollectionViewDelegate

extension CarouselView: UICollectionViewDelegate {

public func scrollViewDidScroll(_ scrollView: UIScrollView) {

let offsetPage = scrollView.contentOffset.x / scrollView.bounds.width

let currentIndex = Int(round(offsetPage))

pageControl.currentPage = currentIndex % (imageURLList?.count ?? 1)

}

public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {

end()

}

public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {

start()

}

}

//  CarsouselCell.swift

//CarsouselCell.xib


import UIKit

class CarsouselCell: UICollectionViewCell {

/// 图片区域

@IBOutlet var imageView: UIImageView!

var imageURL: String? {

didSet{

imageView.sd_setImage(path: imageURL)

}

}

}

//  Extension.swift


import UIKit

import SDWebImage

extension UIImageView {

public func sd_setImage(path: String?) {

guard let noNullPath = path as? NSString else { return }

guard let newPath = noNullPath.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed) else { return }

self.sd_setImage(with: URL(string: newPath))

}

}

到此图片轮播器的代码已经over了

在项目中如何使用呢?

//  ViewController.swift

//  Carousel


import UIKit

import Carousel

class ViewController: UIViewController {

lazy var cv: CarouselView = CarouselView.carouselView()

override func viewDidLoad() {

super.viewDidLoad()

cv.frame = CGRect(x: 0, y: 100, width: UIScreen.main.bounds.width, height: 150)

cv.imageURLList = ["http://www.17sucai.com/preview/569922/2016-06-30/轮播/images/3.jpg", "http://www.17sucai.com/preview/569922/2016-06-30/轮播/images/1.jpg"]

view.addSubview(cv)

}

override func viewWillAppear(_ animated: Bool) {

super.viewWillAppear(animated)

cv.start()

}    

}



鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
[Swift UI]一、基础控件-(5)如何使视图充满整个屏幕发布时间:2022-07-13
下一篇:
JS与原生OC/Swift相互调用总结发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap