最近在做项目的时候用到了,系统默认UICollectionViewController,一般写的时候用的都是UICollectionView,这次用UICollectionViewController遇到了一些问题记录一下
1.不用xib创建时,需要重写
override init(collectionViewLayout layout: UICollectionViewLayout){
super.init(collectionViewLayout: layout)
}
重写后会自动提示添加下面这段函数,这段函数是swift4.0以后都自动提示要加的
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
2.最重要的是layout不能写到viewDidLoad()这样是无效的
override func viewDidLoad() {
super.viewDidLoad()
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: UIScreen.main.bounds.width-20 , height: UIScreen.main.bounds.height-20)
layout.minimumLineSpacing = 15.0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
这样是无效的
必须在convenience init()方法里声明
convenience init() {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
layout.minimumLineSpacing = 15.0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
self.init(collectionViewLayout: layout)
}
接下来就是cell的注册以及调用了
self.collectionView!.register(DataCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
设置返回layout的个数和cell的内容
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return self.leagueNameArr.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! DataCollectionViewCell
cell.titleLabel.text = self.leagueNameArr[indexPath.item]
return cell
}
如果需要设置item的大小以及距离上左下右的距离就得加上UICollectionViewDelegateFlowLayout协议,并遵循一下方法
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize.init(width: 60, height: 30)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets.init(top: 5, left: 10, bottom: 5, right: 10)
}
版权声明:本文为qq_41423782原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。