How to show a message when collection view is empty

前端 未结 5 1269
無奈伤痛
無奈伤痛 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-07 06:39

    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()
        }
    

提交回复
热议问题