自定义了一个banner类。完全凭借OC的感觉写的。话不多说,直接上代码
//
// LHWhellPlantImage.swift
// safari
//
// Created by 磊怀王 on 2019/12/2.
// Copyright © 2019 磊怀王. All rights reserved.
//
import UIKit
class LHWhellPlantImage: NSObject,UIScrollViewDelegate {
override init() {
super.init()
}
/// 轮播图的实现类
/// - Parameters:
/// - imageArr: 原始图片数组 即图片的名字
/// - superView: 所要加载的父视图
/// - rect: 轮播图的位置
func initWhellPantImage(_ imageArr : Array<String>,_ superView : UIView,_ rect : CGRect) -> Void {
let imageScro : UIScrollView = UIScrollView.init()
imageScro.frame = rect
imageScro.backgroundColor = UIColor.black
superView.addSubview(imageScro)
let scroW = imageScro.frame.size.width
let scroH = imageScro.frame.size.height
var newImageArr : Array<String> = Array.init()
newImageArr += imageArr
newImageArr.insert(imageArr.last!, at: 0)
newImageArr.insert(imageArr.first!, at: newImageArr.count)
for tempImage in newImageArr.enumerated() {
print(tempImage)
let imageR : CGRect = CGRect.init(x: scroW * CGFloat(tempImage.offset), y: 0, width: scroW, height: scroH)
let imageV = UIImageView.init(frame: imageR)
imageV.image = UIImage.init(named: tempImage.element)
imageScro.addSubview(imageV)
// 添加点击事件
let tap = UITapGestureRecognizer.init(target: self, action: #selector(touchWhellImage(_:)))
imageV.addGestureRecognizer(tap)
imageV.isUserInteractionEnabled = true
imageV.tag = 100 + tempImage.offset
}
imageScro.contentSize = CGSize.init(width: scroW * CGFloat(newImageArr.count), height: scroH)
imageScro.contentOffset = CGPoint.init(x: scroW, y: 0);
imageScro.isUserInteractionEnabled = true
imageScro.isPagingEnabled = true
imageScro.delegate = self
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let scroW = scrollView.frame.size.width
let pageAll = scrollView.contentSize.width / scroW
let page = scrollView.contentOffset.x / scroW
if page == 0 {
scrollView.contentOffset = CGPoint.init(x: scroW * CGFloat(pageAll - 2), y: 0)
}else if page == (pageAll - 1){
scrollView.contentOffset = CGPoint.init(x: scroW, y: 0)
}
}
@objc func touchWhellImage(_ ges : UITapGestureRecognizer) -> Void {
print("点击了第\(ges.view!.tag - 100)张图片")
}
}
效果图如下:
调用方法
let whell : LHWhellPlantImage = LHWhellPlantImage.init() //需要声明为全局变量
func bannerScroller() -> Void {
let imageArr : Array = ["scroll001","scroll002","scroll003","scroll004","scroll005","scroll006","scroll007","scroll008","scroll009"]
let rect : CGRect = CGRect.init(x: 10, y: 200, width: UIScreen.main.bounds.size.width - 20, height: 100)
whell.initWhellPantImage(imageArr, self.view, rect)
}
下篇微博 我将加上 自定义的轮播图的指示器,请继续关注