很多时候我们需要列表和宫格视图的来回切换,就像苹果的天气应用一样,我之前见过一个用tableview和collectionview来实现这种效果的,我本人不太喜欢这个,那么有没有更好的方法呢?答案是:有

初识UICollectionView

UICollectionView是一个比UITableView更灵活强大的控件。其他怎么使用这个控件这里不讲述,这里只说列表和宫格的切换。我们查看UICollectionView的API,可以发现有这么一个方法:

open func setCollectionViewLayout(_ layout: UICollectionViewLayout, animated: Bool) // transition from one layout to another

他的解释是转换一个布局到另一个布局。这不就是我们想要的嘛,我们实现两个布局,通过该方法,来回切换布局就行了。

接下来我们通过代码来实现

我们创建一个工程,命名为ListAndGrid,我们直接在默认创建的ViewController中先写这么几个属性

var collectionView: UICollectionView!
var datas: [String] {
var d = [String]()
for i in ... {
d.append("\(i)")
}
return d
}

let listLayout = UICollectionViewFlowLayout() // 列表布局

let gridLayout = UICollectionViewFlowLayout() // 宫格布局

接下来我们在viewDidLoad方法中对这几个属性进行初始设置

代码如下

override func viewDidLoad() {
super.viewDidLoad() listLayout.itemSize = CGSize(width: UIScreen.main.bounds.size.width, height: ) gridLayout.itemSize = CGSize(width: (UIScreen.main.bounds.size.width - ) / 3.0, height: )
gridLayout.minimumLineSpacing =
gridLayout.minimumInteritemSpacing = collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: listLayout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UINib.init(nibName: "LabelCell", bundle: nil), forCellWithReuseIdentifier: "LabelCell") collectionView.backgroundColor = UIColor.white
view.addSubview(collectionView)
// Do any additional setup after loading the view, typically from a nib. }

然后实现UICollectionView相应的代理方法

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return datas.count
} func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LabelCell", for: indexPath) as! LabelCell
cell.label.text = datas[indexPath.row]
return cell
}

至此我们已经实现所有基本代码,接下来我们需要触发setCollectionViewLayout这个方法,我这里是在导航控制器上添加了一个item,这里给出触发事件的代码

@IBAction func clickItem(_ sender: UIBarButtonItem) {
if collectionView.collectionViewLayout == listLayout {
collectionView.setCollectionViewLayout(gridLayout, animated: true)
} else {
collectionView.setCollectionViewLayout(listLayout, animated: true)
}
}

运行程序,效果如下图

切换之后改变cell样式

这是cell样式一样的情况,如果我们要在不用的布局中用不同的cell样式该怎么办呢?

我们首先要在viewDidLoad中添加另一个cell的注册代码,以便复用

collectionView.register(UINib.init(nibName: "LabelCell2", bundle: nil), forCellWithReuseIdentifier: "LabelCell2")

然后func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell代理中也需要做一些改变,我们需要区分是哪种布局,改为下面这样

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView.collectionViewLayout == listLayout {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LabelCell", for: indexPath) as! LabelCell
cell.label.text = datas[indexPath.row]
return cell
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LabelCell2", for: indexPath) as! LabelCell2
cell.label.text = datas[indexPath.row]
return cell
}
}

最后关键的地方来了,我们如果用之前的切换布局方法会发现根本达不到目的,我们查看API发现有一个类似的方法是:func setCollectionViewLayout(_ layout: UICollectionViewLayout, animated: Bool, completion: ((Bool) -> Swift.Void)? = nil),这个方法比之前那个多一个完成之后的回调,我们可以利用回调来重新加载一下数据就可以了,这次触发时间里的代码如下:

@IBAction func clickItem(_ sender: UIBarButtonItem) {
if collectionView.collectionViewLayout == listLayout {
collectionView.setCollectionViewLayout(gridLayout, animated: true, completion: { (com) in
if com {
self.collectionView.reloadData()
}
}) } else {
collectionView.setCollectionViewLayout(listLayout, animated: true, completion: { (com) in
if com {
self.collectionView.reloadData()
}
}) }
}

我们是在布局切换完之后又重新刷了一下数据。

运行程序,效果如下

至此,基本的内容已经讲解完,通过这些我们可以完成更复杂的内容

本工程代码请点击下载

利用UICollectionView实现列表和宫格视图的切换的更多相关文章

  1. SharePoint开发 - Excel数据导入到SharePoint自定义列表(数据视图方式)

    博客地址 http://blog.csdn.net/foxdave 本篇讲解一个有些新颖的SharePoint实例应用,给甲方做过项目的都有过体会,数据太多了,客户有Excel,要求实现批量导入. 效 ...

  2. python利用or在列表解析中调用多个函数.py

    python利用or在列表解析中调用多个函数.py """ python利用or在列表解析中调用多个函数.py 2016年3月15日 05:08:42 codegay & ...

  3. [改善Java代码]子列表只是原列表的一个视图

    List接口提供了subList方法,其作用是返回一个列表的子列表.这与String类的subString有点类似.但是他们的功能是否相同?看代码: import java.util.ArrayLis ...

  4. 利用UICollectionView实现瀑布流

    利用UICollectionView实现瀑布流通过自定义布局来实现. - 自定义类继承UICollectionViewLayout: 必须重写的方法有: //决定每个item的位置: - (nulla ...

  5. Jenkins 利用Dashboard View插件管理任务视图

    利用Dashboard View插件管理任务视图   by:授客 QQ:1033553122 步骤 1.  安装Dashboard View插件 说明: 如果无法在线安装,可以选择本地上传方式安装 附 ...

  6. iOS - UICollectionView 瀑布流 添加表头视图的坑

    UICollectionView 瀑布流 添加表头视图的坑 首先是,需求加了个头视图在顶部,在collectionView中的头视图跟TableView的不一样,TableView的表头只要设置tab ...

  7. python3之利用字典和列表实现城市多级菜单

    利用字典和列表实现城市多级菜单 #coding:utf-8 #利用字典和列表实现城市多级菜单 addrIndex = {":"福建"} addrDict = {" ...

  8. C利用可变参数列表统计一组数的平均值,利用函数形式参数栈原理实现指针运算

    //描述:利用可变参数列表统计一组数的平均值 #include <stdarg.h> #include <stdio.h> float average(int num, ... ...

  9. 【逆向工具】IDA使用5-( string、图形化与视图的切换、图形化显示反汇编地址、自动注释、标签使用)

    分析petya病毒时新学会的技巧. IDA技巧1 : string 提取文件中的字符串内容,如果看到一些文件字符串可以定位到关键的函数中. view -> open subview -> ...

随机推荐

  1. Spark算子--filter

    filter--Transformation类算子 代码示例 result    

  2. python利用socketserver实现并发套接字功能

    本文实现利用python的socketserver这个强大的模块实现套接字的并发 目录结构如下: 测试文件请放在server_file文件夹里面 server.py #!/usr/bin/env py ...

  3. 百度分享到qq空间失败

    QQ做了限制的,localhost是不会返回结果的,要用正式域名访问就可以了

  4. dede从www跟目录迁移,网站空间

    图集缩略图表名dede_uploads                    字段url; 图集文章内部的图片表名dede_addonimages        字段imgurls 频道文章列表的图片 ...

  5. CSS3 background-size 属性

    定义和用法 background-size 属性规定背景图像的尺寸. 默认值: auto 继承性: no 版本: CSS3 JavaScript 语法: object.style.background ...

  6. 织梦dede在首页调用留言本

    织梦dedecms在首页调用留言本 . {dede:loop table=dede_guestbook sort=dtime row=10 titlelen=36 typeid=40 if=ische ...

  7. 微信小程序版2048

    最近流行微信"跳一跳"小游戏,我也心血来潮写了一个微信小程序版2048,本篇文章主要分享实现2048的算法以及注意的点,一起来学习吧!(源码地址见文章末尾)   算法 1.生成4* ...

  8. 【翻译】A Next-Generation Smart Contract and Decentralized Application Platform

    原文链接:https://github.com/ethereum/wiki/wiki/White-Paper 当中本聪在2009年1月启动比特币区块链时,他同时向世界引入了两种未经测试的革命性的新概念 ...

  9. TemplateMethod-模板模式

    什么是Template Method模式 在父类中定义处理流程的框架,在子类中实现具体处理的模式就称为Template Mehtod模式.模板模式的关键是:子类可以置换掉父类的可变部分,但是子类却不可 ...

  10. Intellij-@Override报错

    1.设置  File >> Project Structure >> Project 中设置Project language level如下: 2. 设置  File > ...