CollectionView does not work when built into the navigation controller

I have a simple collection browsing test (based on an online tutorial) that works fine separately. But when I insert it into the navigation controller, it stops working. I built a screen in code using (1) creating a headerView (64 pixels high) and added it to the top view. (2) I built a collection view and added it to the headerView.

Here is the code:

import UIKit

class ViewController: UIViewController,
UICollectionViewDelegate, UICollectionViewDataSource,
UINavigationControllerDelegate
{
var collectionView : UICollectionView!
var topView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
    var frame = CGRect(x:0,y:128, width:view.frame.width, height:64)
    topView = UIView(frame:frame)
    self.view.addSubview(topView)

    // CollectionView
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal
    layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
    layout.itemSize = CGSize(width: 50, height: 50)

    frame = CGRect(x: 0, y: 0, width: Int(self.topView.frame.width), height: Int(self.topView.frame.height))
    collectionView = UICollectionView (frame: frame, collectionViewLayout: layout)
    collectionView.dataSource = self
    collectionView.delegate = self
    collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "collectionCell")
    collectionView.backgroundColor = UIColor.green
    self.topView.addSubview(collectionView)

}

//MARK: - CollectionView

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 14
}



func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath as IndexPath)
    for v in cell.subviews {
        v.removeFromSuperview()
    }
    cell.backgroundColor = UIColor.orange

    let label = UILabel(frame: CGRect(x:0 , y:0 , width:50 , height:50))
    label.text = "\(indexPath.item)"
    label.textAlignment = .center
    label.textColor = UIColor.white
    cell.addSubview(label)

    return cell
}

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

+4
source share
1 answer

, . , , , viewDidLoad , . , viewDidAppear ( viewDidLoad), . y 64, , 64. , . , , . , , .

:

    //
//  CustomViewController.swift
//  DSM Tracker
//
//  Created by Syed Tariq on 1/7/17.
//  Copyright © 2017 com.syedtariq. All rights reserved.
//

import UIKit


class ViewController: UIViewController,
    UICollectionViewDelegate,
    UICollectionViewDataSource,
    UINavigationControllerDelegate

{

    var executeOnce = true
    var cellDimensions = [String:Int]()
    var cellHeight = 50
    var cellWidth = 120

    var collectionContainerView: UICollectionView!
    var navBar: UINavigationBar = UINavigationBar()


    // view constants
    var viewY = CGFloat()
    var viewX = CGFloat()
    var viewWidth = CGFloat()
    var viewHeight = CGFloat()


    // gaps from view edge
    let leftGap = CGFloat(20)
    let rightGap = CGFloat(20)


    // navbar constants
    let navBarHeight = CGFloat(64)

    var headerLabels = ["Cell 01","Cell 02","Cell 03","Cell 04","Cell 05","Cell 06","Cell 07","Cell 08","Cell 09","Cell 10","Cell 11","Cell 12","Cell 13","Cell 14","Cell 15","Cell 16"]


    override func viewDidLoad() {
        super.viewDidLoad()
        navBar.backgroundColor = UIColor.green
        executeOnce = true
        viewY = view.frame.origin.y
        viewX = view.frame.origin.x
        viewWidth = view.frame.width
        viewHeight = view.frame.height
    }



    func configureCollectionView () {
        if executeOnce {
            executeOnce = false
            let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
            layout.scrollDirection = .horizontal
            layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
            layout.itemSize = CGSize(width: cellWidth, height: cellHeight)

            let colWidth = viewWidth - leftGap - rightGap
            let colX = viewX + leftGap
            let colY = viewY + navBarHeight
            let colHeight = CGFloat(64)
            let frame = CGRect(x:colX, y:colY, width: colWidth, height: colHeight)
            //let frame = CGRect.zero
            collectionContainerView = UICollectionView (frame: frame, collectionViewLayout: layout)
            collectionContainerView.dataSource = self
            collectionContainerView.delegate = self
            collectionContainerView.autoresizingMask = [.flexibleLeftMargin,.flexibleLeftMargin,.flexibleBottomMargin,.flexibleRightMargin, .flexibleHeight, .flexibleWidth]
            collectionContainerView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "collectionCell")
            collectionContainerView.backgroundColor = UIColor.blue
            collectionContainerView.allowsSelection = true
            collectionContainerView.isScrollEnabled = true
            collectionContainerView.setNeedsDisplay()
            print("collectionContainerView.frame \(collectionContainerView.frame)")
            view.addSubview(collectionContainerView)
        }
    }

    override func viewDidAppear(_ animated: Bool) {
        configureCollectionView()
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        print("headerLabels.count \(headerLabels.count)")
        return  headerLabels.count
    }



    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath as IndexPath)

        for v in cell.subviews {
            v.removeFromSuperview()
        }

        let cellTitle = headerLabels[indexPath.row]
        let cellTitleLines = cellTitle.components(separatedBy: " ")
        let nLabels = cellTitleLines.count

        cell.layer.borderWidth = 1
        cell.layer.cornerRadius = 8
        let labelHeight = cellHeight / cellTitleLines.count
        for i in (0 ..< nLabels) {
            let frame = CGRect(x: 0, y: labelHeight * i, width: cellWidth, height: labelHeight)
            let label1 = UILabel(frame: frame)
            cell.backgroundColor = UIColor.lightGray
            label1.numberOfLines = 1
            label1.text = headerLabels[indexPath.row]
            label1.textAlignment = .center
            label1.textColor = UIColor.black
            label1.clipsToBounds = true
            label1.adjustsFontSizeToFitWidth = true
            label1.text = cellTitleLines[i]
            cell.addSubview(label1)
        }

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
        collectionContainerView.scrollToItem(at:IndexPath(item: indexPath.item, section: 0), at: .centeredHorizontally, animated: false)

        return true
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionContainerView.cellForItem(at: indexPath)
        print("cell = \(cell)")
        collectionContainerView.scrollToItem(at:IndexPath(item: indexPath.item, section: 0), at: .centeredHorizontally, animated: false)
    }


    func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
        return true
    }


    func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
    }



    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    }
}
0

Source: https://habr.com/ru/post/1665424/


All Articles