Handling an empty UITableView. Print a friendly message

前端 未结 22 1154
青春惊慌失措
青春惊慌失措 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:17

    You can add this to your Base class.

    var messageLabel = UILabel()
    
    func showNoDataMessage(msg: String) {
        let rect = CGRect(origin: CGPoint(x: 0, y :self.view.center.y), size: CGSize(width: self.view.bounds.width - 16, height: 50.0))
        messageLabel = UILabel(frame: rect)
        messageLabel.center = self.view.center
        messageLabel.text = msg
        messageLabel.numberOfLines = 0
        messageLabel.textColor = Colors.grayText
        messageLabel.textAlignment = .center;
        messageLabel.font = UIFont(name: "Lato-Regular", size: 17)
        self.view.addSubview(messageLabel)
        self.view.bringSubviewToFront(messageLabel)
    }
    

    Show it like this in the class on getting the data from api.

    func populateData(dataSource : [PRNJobDataSource]){
        self.dataSource = dataSource
        self.tblView.reloadData()
        if self.dataSource.count == 0 {self.showNoDataMessage(msg: "No data found.")}
    }
    

    Hide it like this.

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.dataSource.count > 0 {self.hideNoDataMessage()}
        return dataSource.count
    }
    
    func hideNoDataMessage(){
        messageLabel.removeFromSuperview()
    }
    

提交回复
热议问题