1.描述
An object that manages an ordered collection of data items and presents them using customizable layouts.(一个管理集合数据元素和使用自定义布局展现它们的一个对象)
class UICollectionView : UIScrollView

集合视图(UICollectionView)和表视图大体相同,所以不进行详细介绍.这里只说一下不同之处.
集合是图是可以多列的,而且其布局需要UICollectionViewLayout支持.这是一个抽象类,具体实现需要使用其子类,系统提供给我们一个UICollectionViewFlowLayout,也可以自己集成,根据提供的接口进行实现自定义布局.
关键属性:
minimumLineSpacing //最小行间距
minimumInteritemSpacing //最小item的列间距
itemSize //item的大小,可以不指定,cell会根据自适应设置
sectionInset //每段内容的上下左右内间距
系统会根据Cell大小,minimumLineSpacing,minimumInteritemSpacing,sectionInset来进行行和列的布局.
集合视图也支持Cell的重用,使用方法类型于表视图.
2.代码示例
2.1.storyboard创建方式
添加UICollectionView,会自带一个Cell,对Cell进行设置重用标识


Cell中添加Label

设置Label的tag,用于后面方便获取

设置好集合视图的Layout的关键属性


当Estimate Size为自动时候,Cell Size则不会受到影响,只会根据Cell里内容进行自适应.
设置ViewController为Collection的delegate和dataSource,并且关联Collection对象

代码部分:
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var myCollectionView: UICollectionView!
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 100
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
2
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "defaultCell", for: indexPath)
let label = cell.contentView.viewWithTag(111) as! UILabel
label.text = "Cell:\(indexPath.section)-\(indexPath.item)"
return cell;
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
2.2.xib方式创建
该方式无法自动计算Cell的itemSize,只能通过设置固定大小方式,创建自定义的Cell类

制定Cell的重用标识

核心代码:
import UIKit
class SecondViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var myCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.myCollectionView.register(UINib.init(nibName: "SecondCollectonViewCell", bundle: nil), forCellWithReuseIdentifier: "SecondCollectonViewCell")
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 100
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
2
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell : SecondCollectonViewCell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "SecondCollectonViewCell", for: indexPath) as! SecondCollectonViewCell
cell.configLabel(labelStr: "Cell:\(indexPath.section)-\(indexPath.item)")
return cell;
}
}
import UIKit
class SecondCollectonViewCell: UICollectionViewCell {
@IBOutlet weak var myLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func configLabel(labelStr : String){
self.myLabel.text = labelStr
}
}
2.3.纯代码方式
创建Collection时候需要初始化UICollectionViewFlowLayout,layout的关键属性可以使用属性赋值,也可以使用代理方法赋值
import UIKit
class ThirdViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
var myCollection : UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.navigationItem.title = "代码方式创建"
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 1.0;
layout.minimumInteritemSpacing = 1.0;
//这里不用属性而用方法设置,二者没有区别,用方法可以对制定的item定制
// layout.itemSize = CGSize.init(width: 100, height: 50)
self.myCollection = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: layout)
self.myCollection.backgroundColor = UIColor.white
self.myCollection.translatesAutoresizingMaskIntoConstraints = false
myCollection.register(ThirdCollectionViewCell.self, forCellWithReuseIdentifier: "ThirdCollectionViewCell")
self.myCollection.delegate = self
self.myCollection.dataSource = self
self.view.addSubview(myCollection)
let constraintV = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[myCollection]-0-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["myCollection" : self.myCollection!])
let constraintH = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[myCollection]-0-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["myCollection" : self.myCollection!])
self.view.addConstraints(constraintV)
self.view.addConstraints(constraintH)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize.init(width: 100, height: 50)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 200
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell : ThirdCollectionViewCell = self.myCollection.dequeueReusableCell(withReuseIdentifier: "ThirdCollectionViewCell", for:indexPath) as! ThirdCollectionViewCell
cell.configLabel(labelStr: "Cell:\(indexPath.section)-\(indexPath.item)")
return cell
}
}
import UIKit
class ThirdCollectionViewCell: UICollectionViewCell {
let myLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
self.contentView.addSubview(self.myLabel)
self.myLabel.translatesAutoresizingMaskIntoConstraints = false
self.myLabel.textAlignment = .center
let constraintV = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[myLabel]-0-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["myLabel" : self.myLabel])
let constraintH = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[myLabel]-0-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["myLabel" : self.myLabel])
self.contentView.addConstraints(constraintV)
self.contentView.addConstraints(constraintH)
self.contentView.backgroundColor = UIColor.systemGreen
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configLabel(labelStr : String){
self.myLabel.text = labelStr
}
}
- 工程下载地址:
https://github.com/DeveloperZhang/SwiftStudyDemo
3.总结
UICollectionView是一个最基础常见的视图类,可以参考文档进行深入学习:UIKit->Views and Controls->UICollectionView
网友评论