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
Maybe little bit late but here is little more constraint based solution. Still may help some one.
First create some empty state message (You can also create own, more complex view with image or something).
lazy var emptyStateMessage: UILabel = {
let messageLabel = UILabel()
messageLabel.translatesAutoresizingMaskIntoConstraints = false
messageLabel.textColor = .darkGray
messageLabel.numberOfLines = 0;
messageLabel.textAlignment = .center;
messageLabel.font = UIFont.systemFont(ofSize: 15)
messageLabel.sizeToFit()
return messageLabel
}()
Then add two methods and call them whenever you like.
func showEmptyState() {
collectionView.addSubview(emptyStateMessage)
emptyStateMessage.centerXAnchor.constraint(equalTo: collectionView.centerXAnchor).activate()
emptyStateMessage.centerYAnchor.constraint(equalTo: collectionView.centerYAnchor).activate()
}
func hideEmptyState() {
emptyStateMessage.removeFromSuperview()
}