ios版本11/12
尝试为UIViewController
设置动态单元格高度(单元格包含具有固定高度的图像,并且标签可以是多行,因为该标签视图单元格应该能够动态更改高度)。我正在使用Storyboard构建具有一些限制的基本UI,这些限制使单元格的最小宽度为300。
在UIViewController的垂直滚动过程中获得奇怪的UI行为。某些单元格(最初不在UI中)的大小调整为情节提要约束中定义的大小,并忽略了estimatedItemSize
import UIKit
class StartController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
let offers = SearchCategoryOffer.mockOffers
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.view.backgroundColor = UIColor.white
let titleImageView = NavigationImageView()
titleImageView.image = UIImage(named: "logo")
navigationItem.titleView = titleImageView
let w = self.collectionView.frame.width - 30
collectionView.delegate = self
collectionView.dataSource = self
collectionView.translatesAutoresizingMaskIntoConstraints = false
if let layout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.sectionInsetReference = .fromLayoutMargins
layout.sectionInset = UIEdgeInsetsMake(20, 5, 20, 5)
layout.minimumLineSpacing = 26
layout.minimumInteritemSpacing = 0
layout.estimatedItemSize = CGSize(width: w, height: 300) // cell size
}
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return offers.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: OfferCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! OfferCell
cell.listTitle?.text = offers[indexPath.row].name
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let _: OfferCell = collectionView.cellForItem(at: indexPath) as! OfferCell
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let _: OfferCell = collectionView.cellForItem(at: indexPath) as! OfferCell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// bla-bla-bla
}
}
class NavigationImageView: UIImageView {
override func sizeThatFits(_ size: CGSize) -> CGSize {
return CGSize(width: 133, height: 35)
}
}