Почему методы UICollectionViewDelegateFlowLayout не вызываются специально в портретном режиме вращения устройства?

У меня есть представление коллекции внутри UIView. Я хочу автоматически изменять размер ячейки при повороте устройства (т.е. будет 4 столбца в режиме портрет и 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
    }
}

comment
Вы правильно подключили делегирование и источник данных к своему контроллеру представления?   -  person Rumy    schedule 29.04.2018
comment
@Rumy, я использую UIView, коллекция находится в стороне UIView. Да, я правильно подключил ваш делегат и источник данных. Пожалуйста, посмотрите мой обновленный код.   -  person M. Ram    schedule 29.04.2018
comment
Могу ли я увидеть ваш код ViewController на github или на любом другом хостинге? Увидев ваш код, я могу вам помочь. Обычно этого не должно происходить.   -  person Rumy    schedule 29.04.2018
comment
Пожалуйста, посмотрите мой обновленный код.   -  person M. Ram    schedule 29.04.2018
comment
хммм. подожди, я пытаюсь разобраться.   -  person Rumy    schedule 29.04.2018
comment
дайте мне знать, решена ли ваша проблема?   -  person Rumy    schedule 29.04.2018
comment
@Rumy, я использую UIView (четко упомянуто), как я могу переопределить viewWillTransition?   -  person M. Ram    schedule 29.04.2018


Ответы (1)


Отметьте viewwilltransition или viewDidLayoutSubviews и обновите свой itemsize по своему усмотрению. Чтобы узнать больше о viewwilltransition и viewDidLayoutSubviews отображают ссылки.

override func viewWillTransition(to size: CGSize, with coordinator: 
         UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    updateCV(with: size)
}

Здесь, если происходит переход просмотра, я вызываю имя метода updateCV, и в этом методе я обновляю itemsize по своему усмотрению.

func updateCV(with size: CGSize) {
    if let layout = cv.collectionViewLayout as? UICollectionViewFlowLayout 
     {
      // add your custom layout here
        layout.itemSize = (size.width < size.height) ? itemSizeForPortraitMode : itemSizeForLandscapeMode
        layout.invalidateLayout()
    }
}
person Rumy    schedule 29.04.2018
comment
Я использую UIView (четко упомянуто), как я могу переопределить viewWillTransition? - person M. Ram; 29.04.2018