У меня есть представление коллекции внутри UIView. Я хочу автоматически изменить размер ячейки при повороте устройства (то есть будет 4 столбца в режиме potrait и 5 столбцов в режиме ландшафт ). В первый раз (при первом запуске приложения) все работало нормально, но когда я снова переключаю устройство в портретный режим из ландшафтного режима, методы делегирования FlowLayout не вызывают.
Вот мой код:
class GridViewNw: UIView, UICollectionViewDelegate {
var gridCollectionView: UICollectionView!
var imgArrCount: Int = 20
var gridLeading: NSLayoutConstraint?
var gridTrailing: NSLayoutConstraint?
var gridTop: NSLayoutConstraint?
var gridBottom: NSLayoutConstraint?
var gridWidth: NSLayoutConstraint?
var gridLeft: NSLayoutConstraint?
var gridRight: NSLayoutConstraint?
var gridCenter: NSLayoutConstraint?
override init(frame: CGRect) {
super.init(frame: frame)
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
gridCollectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
gridCollectionView.dataSource = self
gridCollectionView.delegate = self
gridCollectionView.register(GridViewCell.self, forCellWithReuseIdentifier: "gridViewCell")
gridCollectionView.backgroundColor = UIColor.yellow
gridCollectionView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(gridCollectionView)
gridTop = gridCollectionView.topAnchor.constraint(equalTo: self.topAnchor, constant: 0)
gridTop?.isActive = true
gridCenter = gridCollectionView.centerXAnchor.constraint(equalTo: self.centerXAnchor)
gridCenter?.isActive = true
gridLeft = gridCollectionView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0)
gridLeft?.isActive = true
gridRight = gridCollectionView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0)
gridRight?.isActive = true
gridBottom = gridCollectionView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0)
gridBottom?.isActive = true
gridCollectionView!.collectionViewLayout = layout
//NotificationCenter.default.addObserver(self, selector: #selector(self.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
//layout.prepare()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func getImgSize() -> (width: CGFloat, height: CGFloat, itemGap: CGFloat, collVwWidth: CGFloat){
var imgWidth: CGFloat = 115
var imgHeight: CGFloat = 173
let viewWidth: CGFloat = self.bounds.width
var columnCount: Int = 3
if UIDevice.current.userInterfaceIdiom == .pad {
imgWidth = 157
imgHeight = 236
columnCount = 4
let interfaceOrientation: UIInterfaceOrientation = UIApplication.shared.statusBarOrientation
if interfaceOrientation == .landscapeLeft || interfaceOrientation == .landscapeRight {
columnCount = 5
}
}
let gapCount: Int = columnCount - 1 //CGFloat(columnCount * 2) //CGFloat(columnCount - 1)
let minimumGap: CGFloat = 10
var totalGap: CGFloat = minimumGap * CGFloat(gapCount)
var collectionViewWidth: CGFloat = viewWidth - totalGap
let remainder = Int(collectionViewWidth) % columnCount
totalGap = totalGap + CGFloat(remainder)
let itemGap = totalGap / CGFloat(gapCount)
collectionViewWidth = collectionViewWidth - CGFloat(remainder)
let itemWidth: CGFloat = (collectionViewWidth - totalGap) / CGFloat(columnCount) //(collectionViewWidth / CGFloat(columnCount)) - (minimumGap * 2)
let itemHeight: CGFloat = (imgHeight / imgWidth) * itemWidth
return (itemWidth, itemHeight, itemGap, collectionViewWidth)
}
}
extension GridViewNw: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imgArrCount
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let imageCell : GridViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridViewCell", for: indexPath) as! GridViewCell
//imageCell.contentView.backgroundColor = UIColor.blue
let img = getImgSize()
imageCell.displayAssetImage(imgWidth: img.width, imgHeight: img.height)
imageCell.layer.shouldRasterize = true
imageCell.layer.rasterizationScale = UIScreen.main.scale
return imageCell
}
}
extension GridViewNw : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
print("sizeForItemAt")
let img = getImgSize()
return CGSize(width: img.width, height: img.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
print("insetForSectionAt")
let img = getImgSize()
return UIEdgeInsetsMake(0, img.itemGap, 0, img.itemGap)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
print("minimumInteritemSpacingForSectionAt")
let img = getImgSize()
return img.itemGap
}
}