ios - UICollectionView 两个具有相同 View 的单元格。第二个单元格什么也没显示

标签 ios swift uicollectionview uicollectionviewcell

什么会导致这种行为?我有一个带有两个单元格的 Collection View 。两个单元格应具有相同的 View 但不同的文本内容。第二个单元格中什么也没有显示。我在“cellforrowat”中做错了什么吗?我错过了什么?

Dragon DragonExtra

class UpgradeController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource,UIScrollViewDelegate{


    let numMonths = ["1","6","12"]
    let months = ["month","months","months"]
    let prices = ["$19.99","$79.99","$99.99"]
    let pricePerMonth = ["","($13.33 per month)","($8.33 per month)"]
    let pricesExtra = ["$29.99","119.99","149.99"]
    let pricePerMonthExtra = ["","$19.99 per month","$12.49 per month"]



    var collectionView:UICollectionView!
    var scrollView:UIScrollView!

    let cellId = "cellId"
    let cellId2 = "cellId2"


    override func viewDidLoad() {

        super.viewDidLoad()
        self.setupViews()


    }


    func setupViews(){
        let statusBarHeight: CGFloat = UIApplication.shared.statusBarFrame.size.height
        let navBarHeight: CGFloat = self.navigationController!.navigationBar.frame.height
        let tabBarheight: CGFloat = self.tabBarController!.tabBar.frame.height
        let displayWidth: CGFloat = self.view.frame.width
        let displayHeight: CGFloat = self.view.frame.height


        //view.setGradientBackgroundColor(colorOne: UIColor(rgb:0x000000), colorTwo: UIColor(rgb:0x056644))
        navigationController?.navigationBar.isTranslucent = false

        setupCollectionView()
        setupMenuBar()


        scrollView = UIScrollView()
        scrollView.backgroundColor = .clear //.orange
        scrollView.delegate = self
        scrollView.frame = CGRect(x:0,y:50,width:UIScreen.main.bounds.width,height:UIScreen.main.bounds.height)


        if let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout{
            flowLayout.scrollDirection = .horizontal    //= .horizontal
        }
        scrollView.addSubview(self.collectionView)
        self.view.addSubview(scrollView)
    }

Collection View 设置:

    func setupCollectionView(){

        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 120, right: 0)
        //layout.itemSize = CGSize(width: screenWidth / 3, height: screenWidth / 3)
        //layout.itemSize = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0

        collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
        collectionView.collectionViewLayout = layout
        collectionView.dataSource = self
        collectionView.delegate = self

        collectionView?.register(DragonCell.self, forCellWithReuseIdentifier: cellId)


        collectionView!.backgroundColor = UIColor.clear

        collectionView.contentInset = UIEdgeInsets(top: 0,left: 0,bottom: 0,right: 0)
        collectionView.isPagingEnabled = true

        self.view.addSubview(collectionView)
    }


    let titles = ["Dragon", "DragonExtra"]

    lazy var menuBar: MenuBar = {
        let mb = MenuBar()
        mb.backgroundColor = .red
        mb.translatesAutoresizingMaskIntoConstraints = false
        mb.names = ["Dragon", "DragonExtra"]
        mb.upgradeController = self

        return mb
    }()

    private func setupMenuBar(){

        menuBar.setupHorizontalBar()
        //menuBar.multiplier = CGFloat(1/8.0)
        view.addSubview(menuBar) //view.addSubview(menuBar)
        view.addConstraintsWithFormat("H:[v0(\(view.frame.width*CGFloat(menuBar.names.count)/4.0))]", views: menuBar)
        view.addConstraintsWithFormat("V:|[v0(50)]|", views: menuBar)
        view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[v1]-(<=1)-[v0]", options: NSLayoutConstraint.FormatOptions.alignAllCenterX, metrics: nil, views: ["v0":menuBar,"v1":self.view])) //center horizontally
    }

    func scrollToMenuIndex(menuIndex:Int){
        let indexPath = NSIndexPath(item: menuIndex, section: 0)
        collectionView.scrollToItem(at: indexPath as IndexPath, at: [], animated: true)

        //setTitleForIndex(index:menuIndex)
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //menuBar.horizontalBarLeftAnchorConstraint?.constant = scrollView.contentOffset.x/2 + view.frame.width/8.0
        menuBar.horizontalBarLeftAnchorConstraint?.constant = scrollView.contentOffset.x/CGFloat(titles.count*2)
    }


    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

        let index = targetContentOffset.pointee.x / view.frame.width
        let indexPath = NSIndexPath(item: Int(index), section: 0)
        menuBar.collectionView.selectItem(at: indexPath as IndexPath, animated: true, scrollPosition: [])
        //setTitleForIndex(index:Int(index))
    }


    private func setTitleForIndex(index:Int){
        /*
         if let titleLabel = navigationItem.titleView as? UILabel{
         titleLabel.text = titles[Int(index)]
         }
         */
    }

Collection View 委托(delegate)方法:

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

  func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

  }

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
  {

      print(indexPath.item)
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! DragonCell
      switch indexPath.item{
        case 0:
          cell.numMonths = numMonths
          cell.months = months
          cell.prices = prices
          cell.pricePerMonth = pricePerMonth
          cell.backgroundColor = .blue

          return cell
        case 1:
          cell.numMonths = numMonths
          cell.months = months
          cell.prices = pricesExtra
          cell.pricePerMonth = pricePerMonthExtra
          cell.backgroundColor = .red

          return cell

        default:
          let cell = UICollectionViewCell() //collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
          return cell
      }

  }



  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
      return CGSize(width:view.frame.width,height:view.frame.height)
  }


}

最佳答案

从我在您的代码中看到的内容来看,您想要重用相同的 Collection View 但只是更改内容?

那么为什么不根据选择的菜单栏项目设置一个条件呢?

像这样...

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{

    print(indexPath.item)
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! DragonCell

    //Not exactly sure if this is correct for what you have written 
//for your code. But the idea is take the index that is shown or active //from your menu bar. 
//You have used a switch statement which used the collection view //index. not the menubar index
    if menuBar.index == 0 {
        cell.numMonths = numMonths
        cell.months = months
        cell.prices = prices
        cell.pricePerMonth = pricePerMonth
        cell.backgroundColor = .blue

        return cell
    } else {
        cell.numMonths = numMonths
        cell.months = months
        cell.prices = pricesExtra
        cell.pricePerMonth = pricePerMonthExtra
        cell.backgroundColor = .red

        return cell
    }
    //switch indexPath.item{
      //case 0:
        //cell.numMonths = numMonths
        //cell.months = months
        //cell.prices = prices
        //cell.pricePerMonth = pricePerMonth
        //cell.backgroundColor = .blue

        //return cell
      //case 1:
        //cell.numMonths = numMonths
        //cell.months = months
        //cell.prices = pricesExtra
        //cell.pricePerMonth = pricePerMonthExtra
        //cell.backgroundColor = .red

        //return cell

      //default:
        //let cell = UICollectionViewCell() //collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
        return cell
    }

}

看起来您在 switch 语句中正在使用 Collectionview 的索引路径。但是您不想根据所选菜单栏的索引路径显示内容吗?

但是,我会采用完全不同的方法并为其他 View 创建第二个 Collection View 。

关于ios - UICollectionView 两个具有相同 View 的单元格。第二个单元格什么也没显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59564966/

相关文章:

ios - 在 Swift 中使用视觉格式通过约束格式化 TextView

ios - 如何使用自动布局以编程方式快速设置旋转时 UICollectionView 的宽度

ios - 注册大量 UICollectionViewCell 类以在 UICollectionView 中重用

Swift:如何一次启用或禁用嵌入自定义类中的多个按钮?

ios - 如何在 Swift 中将代理对转换为 Unicode 标量

ios - 搜索栏工作正常,但当我想设置表格单元格标签时崩溃

ios - 在 Swift Playground 中演奏音符

ios - 我怎样才能圆容器 TableView 的角落?

Android 相当于 textViewShouldBeginEditing

swift - 无法在 Swift 的数组中复制随机播放