How to show a message when collection view is empty

前端 未结 5 1358
無奈伤痛
無奈伤痛 2021-02-07 05:54

I`m trying to show a message only when my collection view is empty. Well, I try set return 1 when my if is true but when I have this, it only show one item in my collection view

5条回答
  •  半阙折子戏
    2021-02-07 06:54

    I would say have two sections in your collectionView, where one is for the actual data to be displayed, then the other one when you don't have any data.

    Assuming we are populating data in section 0.

    in numberOfRowsInSection you'd have something like:

         if section == 0 { return movies.count}
         else if section == 1 {
              if movies.count < 1 { return 1 }
              else { return 0  }
         }
            return 0
    

    in your cellForItemAt you'd do something like that:

     if indexPath.section == 0 {
          // let cell = ...
          // show your data into your cell 
            return cell  
         }else {
              // here you handle the case where there is no data, but the big thing is we are not dequeuing  
              let rect = CGRect(x: 0, y: 0, width: self.favCollectionView.frame.width, height: self.favCollectionView.frame.height)
            let noDataLabel: UILabel = UILabel(frame: rect)
            noDataLabel.text = "No favorite movies yet."
            noDataLabel.textAlignment = .center
            noDataLabel.textColor = UIColor.gray
            noDataLabel.sizeToFit()
    
            let cell = UICollectionViewCell()
            cell.contentView.addSubview(noDataLabel)
    
           return cell
          }
    

提交回复
热议问题