Swift   发布时间:2022-04-29  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了uicollectionview – 嵌入在Navigation Controller中时,CollectionView不起作用大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个简单的集合视图测试(基于在线教程),它独立工作.但是当我将它嵌入导航控制器时,它就会停止工作.我在代码中构建了屏幕:(1)创建一个headerView(64像素高)并将其添加到顶部的视图中. (2)我构建了一个集合视图并将其添加到headerView中.

这是代码

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.
}

}

解决方法

如上所述,我无法使查尔的建议工作.它确实给了我一个线索,我对嵌入集合视图的视图的定位在viewDidLoad中被错放了,原因我还没理解.但是,通过将集合视图配置放在viewDidAppear(而不是viewDidLoad)中,它运行良好.我将y位置偏移64以清除导航栏,并将行高减少到64.我还将代码只执行一次,以便页面导航不会添加多个彼此顶部的视图.顺便说一句,我最初的目标是水平滚动细胞.在我的程序中,我有相应部分的tableview,并且想法是使用具有水平滚动单元格的行移动到相应的部分.

代码如下所示:

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

import UIKit


class ViewController: UIViewController,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,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,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?) {
    }
}

大佬总结

以上是大佬教程为你收集整理的uicollectionview – 嵌入在Navigation Controller中时,CollectionView不起作用全部内容,希望文章能够帮你解决uicollectionview – 嵌入在Navigation Controller中时,CollectionView不起作用所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。