Handling an empty UITableView. Print a friendly message

前端 未结 22 1144
青春惊慌失措
青春惊慌失措 2020-12-04 05:22

I have a UITableView that in some cases it is legal to be empty. So instead of showing the background image of the app, I would prefer to print a friendly message in the scr

22条回答
  •  北海茫月
    2020-12-04 06:18

    I made a few changes so that we don't need to check on the count manually, also i added constraints for the label so that nothing goes wrong no matter how large is the message as shown below:

    extension UITableView {
    
        fileprivate func configureLabelLayout(_ messageLabel: UILabel) {
            messageLabel.translatesAutoresizingMaskIntoConstraints = false
            let labelTop: CGFloat = CGFloat(UIDevice.current.userInterfaceIdiom == .pad ? 25:15)
            messageLabel.topAnchor.constraint(equalTo: backgroundView?.topAnchor ?? NSLayoutAnchor(), constant: labelTop).isActive = true
            messageLabel.widthAnchor.constraint(equalTo: backgroundView?.widthAnchor ?? NSLayoutAnchor(), constant: -20).isActive = true
            messageLabel.centerXAnchor.constraint(equalTo: backgroundView?.centerXAnchor ?? NSLayoutAnchor(), constant: 0).isActive = true
        }
    
        fileprivate func configureLabel(_ message: String) {
            let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height))
            messageLabel.textColor = .black
            messageLabel.numberOfLines = 0
            messageLabel.textAlignment = .center
            let fontSize = CGFloat(UIDevice.current.userInterfaceIdiom == .pad ? 25:15)
            let font: UIFont = UIFont(name: "MyriadPro-Regular", size: fontSize) ?? UIFont()
            messageLabel.font = font
            messageLabel.text = message
            self.backgroundView = UIView()
            self.backgroundView?.addSubview(messageLabel)
            configureLabelLayout(messageLabel)
            self.separatorStyle = .none
        }
    
        func setEmptyMessage(_ message: String, _ isEmpty: Bool) {
            if isEmpty { // instead of making the check in every TableView DataSource in the project
                configureLabel(message)
            }
            else {
                restore()
            }
    
        }
    
        func restore() {
            self.backgroundView = nil
            self.separatorStyle = .singleLine
        }
    }
    

    Usage

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            let message: String = "The list is empty."
            ticketsTableView.setEmptyMessage(message, tickets.isEmpty)
            return self.tickets.count
        }
    

提交回复
热议问题