[英]Swift reload data collectionview when changing segmentation control
我有一個collectionview,每個單元格顯示2個圖像,在header中我有分割控制。 當第一次加載一切正常時,我可以在每個單元格中看到兩個圖像,但是當我更改分割時,我可以在單元格中看到一個圖像並且第一個圖像比其他圖像大。
我的錯誤是什么,我的代碼中缺少什么? 我想在單元格中看到兩個圖像,所有圖像都應該是相同的大小
我的代碼:
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.register(UINib.init(nibName: "cell", bundle: nil), forCellWithReuseIdentifier: "cell")
self.collectionView.dataSource = self
self.collectionView.delegate = self
addSegmentationControl()
}
func addSegmentationControl(){
let items = [first, second]
segmentedController = UISegmentedControl(items: items)
segmentedController.selectedSegmentIndex = 0
segmentedController.addTarget(self, action: #selector(TopMediasViewController.segmentedControlActionChanged(_:)), for: .valueChanged)
navigationItem.titleView = segmentedController
}
@objc func segmentedControlActionChanged(_ sender: UISegmentedControl) {
//self.collectionView.reloadData()
self.collectionView.reloadItems(at: collectionView.indexPathsForVisibleItems)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
var returnValue = 0
switch(segmentedController.selectedSegmentIndex)
{
case 0:
returnValue = firstData.count
break
case 1:
returnValue = secondData.count
break
default:
break
}
return returnValue
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt
indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! TopMediasCollectionViewCell
switch(segmentedController.selectedSegmentIndex)
{
case 0:
medias = self.firstData
break
case 1:
medias = self.secondData
break
default:
break
}
let media = medias[indexPath.row]
let imageUrl = media.mediaImageUrl
AF.request(imageUrl).responseImage { response in
switch response.result {
case .success(let image):
cell.imgView.image = image
case .failure(let error):
print(error)
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let noOfCellsInRow = 2
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
flowLayout.minimumInteritemSpacing = 0
let totalSpace = flowLayout.sectionInset.left
+ flowLayout.sectionInset.right
+ (flowLayout.minimumInteritemSpacing * CGFloat(noOfCellsInRow - 1))
let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(noOfCellsInRow))
return CGSize(width: size, height: (size / 4 * 3))
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.