How to show a message when collection view is empty

前端 未结 5 1282
無奈伤痛
無奈伤痛 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:30

    I make use of the backgroundView in an extension as such:

    extension UICollectionView {
    
        func setEmptyMessage(_ message: String) {
            let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height))
            messageLabel.text = message
            messageLabel.textColor = .black
            messageLabel.numberOfLines = 0;
            messageLabel.textAlignment = .center;
            messageLabel.font = UIFont(name: "TrebuchetMS", size: 15)
            messageLabel.sizeToFit()
    
            self.backgroundView = messageLabel;
        }
    
        func restore() {
            self.backgroundView = nil
        }
    }
    

    and I use it as such:

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    
        if (self.movies.count == 0) {
            self.collectionView.setEmptyMessage("Nothing to show :(")
        } else {
            self.collectionView.restore()
        }
    
        return self.movies.count
    }
    

提交回复
热议问题