16.无限轮播之数据请求
2017-09-01 本文已影响18人
whong736
6.请求轮播数据
6.1网络请求继续封装在ViewModel中
懒加载一个轮播模型数据
//懒加载 CycleModel 模型,将解析的结果存在对象数组中
lazy var cycleModels : [CycleModel] = [CycleModel]()

发送网络请求
// MARK:请求轮播数据,传入一个闭包的参数
func requestCycleData(_ finishCallback : @escaping () -> ()){
NetworkTools.requestData(.get, URLString: "http://www.douyutv.com/api/v1/slide/6", parameters: ["version" : "2.300"]) { (result) in
// 1.获取整体字典数据
guard let resultDict = result as? [String : NSObject] else { return }
// 2.根据data的key获取数据
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return }
//字典转模型对象
for dict in dataArray {
self.cycleModels.append(CycleModel(dict: dict))
}
finishCallback()
print("请求轮播数据")
}
}

6.2 回到ViewModel对应的Controller中
调用请求数据方法

6.3 解析请求到的json数据,进行解析,分析,需要定义的Model的字段,如果JSON的API也是自己写的,可以略过这步

确定好,需要的model字段后,开始新建无限轮播Model


定义Model的字段

回到ViewModel中,懒加载一个全局的轮播对象模型数组,用于存储转化后的对象,在我们之前打印请求数据结果的地方,将打印结果改成解析数据

在View中定义一个模型属性

在Controller中进行赋值

请求到的数据赋值非模型
func requestCycleData(_ finishCallback : @escaping () -> ()) {
NetworkTools.requestData(.get, URLString: "http://127.0.0.1:8000/api/cycleImg/", parameters: ["format" : "json"]) { (result) in
//1.将result转成字典类型
guard let resultDict = result as? [String: Any] else { return }
//2.将字典转成数组
guard let dataArray = resultDict["results"] as? [[String : Any]] else { return }
// 3.字典转模型对象
for dict in dataArray {
self.cycleModels.append(CycleModel(dict: dict))
}
finishCallback()
}
}

view中对传递过来的值进行处理
//定义模型属性
var cycleModels : [CycleModel]?{
//监听属性控件值的改变
didSet{
//刷新数据
collectionView.reloadData()
pageControl.numberOfPages = cycleModels?.count ?? 0
}
}


CollectionView 绑定请求到的数据源:,原来我们为了显示,直接返回的固定的值
//MARK:遵循collectionView的数据源协议
extension RecommenCycleView: UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return cycleModels?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCycleCellID, for: indexPath)
let cycleModel = cycleModels![indexPath.item]
// 根据奇偶数,设定不同的背景颜色,方便查看效果
cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.red :UIColor.blue
return cell
}
}

运行查看效果:

马哥24
让Cell对请求到的数据进行展示:
新建一个UICollectionViewCell

选择类型为 UICollectionViewCell 勾选创建XIB文件

到轮播View之前注册cell的地方
// MARK:2.注册Cell
//collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kCycleCellID)
//修改为使用XIB进行注册
collectionView.register(UINib(nibName: "CollectionCycleCell", bundle: nil), forCellWithReuseIdentifier: kCycleCellID)
修改之前:

修改为XIB注册

到定义collectionView的地方将cell强转为我们定义的XIB cell

到collectionCycleCell
删除垃圾代码,定义模型属性


回到View中 删除背景的图片,修改cell

到XIB进行控件设置
拖入一个图片控件,并设定约束

在图片控件上方放一个半透明的黑色背景条 选择背景颜色后,选择其他,在透明度上修改为30%

黑色透明背景条也设置约束




这时候就搞定了文字和背景
还可以设置默认的图片


运行查看效果:

定义控件属性
将model的数值传递给控件进行显示

//
// CollectionCycleCell.swift
// BagStore
//
// Created by vincentwen on 17/9/2.
// Copyright © 2017年 vincentwen. All rights reserved.
//
import UIKit
import Kingfisher
class CollectionCycleCell: UICollectionViewCell {
@IBOutlet weak var cycleImage: UIImageView!
@IBOutlet weak var cycleLable: UILabel!
//MARK:定义模型属性
var cycleModel : CycleModel?{
didSet{
cycleLable.text = cycleModel?.title
//定义图片地址
let ImaURL = URL(string: cycleModel?.pic_url ?? "")!
// 使用kingfisher来设置图片,并添加占位图
cycleImage.kf.setImage(with: ImaURL, placeholder: UIImage(named: "Img_default"))
}
}
}

运行查看效果:

设置滚动的内容,跟右下角的圆点保持一致
设置CycleView的代理
collectionView.delegate = self

实现代理的协议
//MARK: 遵循collection 代理协议
extension RecommenCycleView : UICollectionViewDelegate{
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//1.滚动的偏移量,加上 0.5 让滚动到一半后自动加载到另一半。即默认帮他先多加载50%
let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5
//2.计算pageController的currentIndex
pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (cycleModels?.count ?? 1)
}
}

运行查看效果,滚动图片,小标点也会跟着移动

马哥 25