图片轮播器(swift)

简介: 如何实现一个无限循环,无缝衔接的图片轮播器 自己实现一次以后就不用使用轮播器的框架了能用代码解决的问题就不在这里瞎BB了  O(∩_∩)O首先先在Carousel文件件夹创建以下几个文件CarouselFlowLayout.

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

能用代码解决的问题就不在这里瞎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


img_67085e78dd18c08fe664d0aaf1243dd2.png

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


img_bbb9ebefddbf934d8d563afa0bc597b7.png

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()

}    

}


目录
相关文章
|
Swift
Swift - 根据图片URL获取图片的大小
Swift - 根据图片URL获取图片的大小
470 0
|
缓存 Swift iOS开发
iOS开发swift版异步加载网络图片(带缓存和缺省图片)
iOS开发swift版异步加载网络图片(带缓存和缺省图片)
424 0
|
索引
SWIFT用ScrollView加图片制作Banner
网上参考OBJC写的用ScrollView图片轮播效果,照着画了个,先上效果图: 附上代码: 1 @IBOutlet weak var pc: UIPageControl! 2 @IBOutlet weak var sv:UIScrollView! 3 4...
753 0
|
Swift
swift UIImage加载远程图片和圆角矩形
  原文地址:http://www.cnblogs.com/sxlfybb/p/3791973.html UIImage这个对象是swift中的图像类,可以使用UIImageView加载显示到View上。
1298 0
|
存储 Swift
Swift Core Data 图片存储与读取Demo
实体的模型定义: 实体的class定义: @objc(ImageEntity) class ImageEntity: NSManagedObject { @NSManaged...
1018 0
|
Swift
swift UI专项训练36 ImageVi图片边框阴影
    ImageView是我们经常用到的组件,但是我们发现storyboard中图片的属性编辑器中没有对于图片边框的设计。
923 0
|
缓存 Swift 数据安全/隐私保护
|
3月前
|
安全 编译器 Swift
IOS开发基础知识: 对比 Swift 和 Objective-C 的优缺点。
IOS开发基础知识: 对比 Swift 和 Objective-C 的优缺点。
89 2
|
2月前
|
监控 API Swift
用Swift开发iOS平台上的上网行为管理监控软件
在当今数字化时代,随着智能手机的普及,人们对于网络的依赖日益增加。然而,对于一些特定场景,如家庭、学校或者企业,对于iOS设备上的网络行为进行管理和监控显得尤为重要。为了满足这一需求,我们可以利用Swift语言开发一款iOS平台上的上网行为管理监控软件。
181 2

相关课程

更多