【发布时间】:2020-05-16 22:03:24
【问题描述】:
我最近一直在学习 UICollectionViews,我目前正在尝试实现一个。我需要显示两列,但无论我做什么,它都默认为一列。这里有很多类似的问题,建议使用collectionView 函数sizeForItemAt 调整 UICollectionView 单元格的宽度,但我似乎无法让它工作。
这是我的视图控制器代码:
class PreferencesViewController: UIViewController {
lazy var collectionView : UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = UICollectionView.ScrollDirection.vertical
let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
cv.translatesAutoresizingMaskIntoConstraints = false
cv.register(CategorySelectorCell.self, forCellWithReuseIdentifier: "categorySelector")
cv.backgroundColor = .clear
return cv
}()
override func viewDidLoad(){
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(collectionView)
collectionView.backgroundColor = .blue
collectionView.contentInsetAdjustmentBehavior = .always
collectionView.delegate = self
collectionView.dataSource = self
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20).isActive = true
collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20).isActive = true
collectionView.topAnchor.constraint(equalTo: view.topAnchor, constant: 40).isActive = true
collectionView.heightAnchor.constraint(equalToConstant: view.frame.height/1.5).isActive = true
self.view = view
}
}
我的代理扩展:
extension PreferencesViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "categorySelector", for: indexPath) as! CategorySelectorCell
cell.cat = categories[indexPath.section]
cell.backgroundColor = .red
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width/2.5, height: collectionView.frame.width/2)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
10
}
}
任何指针表示赞赏!
【问题讨论】:
标签: ios swift uicollectionview