close

Show image and label if row count is zero in UITableView using swift 3

QuestionsCategory: SwiftShow image and label if row count is zero in UITableView using swift 3
Taimoor asked 2 weeks ago

When my tableView’s row count is zero I am successfully display a “No Result Label“. But I want to display an image above the UILabel in “numberOfRowsInSection”. How can I do that in swift 3 please.

1 Answers
Best Answer
Chaudhary Talha Staff answered 2 weeks ago

You need a to make a custom UIView and then give it the backgroundView of your UITableView. Imagine the image size is 50×50 so your methods will go like:

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        let noDataLabel: UILabel = UILabel(frame: CGRect(x: 0, y: 50, width: tableView.bounds.size.width, height: tableView.bounds.size.height))
        
        let image = UIImage(named: "noData")
        let noDataImage = UIImageView(image: image)
        
        noDataImage.contentMode = UIViewContentMode.scaleAspectFit
        
        noDataImage.frame = CGRect(x: tableView.center.x-25, y: 0, width: 50, height: tableView.bounds.size.height)

        let backgroundView = UIView(frame: CGRect(x:0, y: 0, width: tableView.bounds.size.width, height: tableView.bounds.size.height))
        
        if allData.count == 0 {
            
            noDataLabel.isHidden = false
            noDataImage.isHidden = false

            noDataLabel.text          = "No data available. Add new entry \nby pressing the + icon on top right."
            noDataLabel.textColor     = UIColor.black
            noDataLabel.numberOfLines = 3
            noDataLabel.backgroundColor = UIColor.white
            noDataLabel.textAlignment = .center
            backgroundView.addSubview(noDataLabel)
            backgroundView.addSubview(noDataImage)
            
            tableView.backgroundView=backgroundView

            tableView.separatorStyle  = .none
            return 0;
        }
        else {
            noDataLabel.backgroundColor = UIColor.clear
            noDataLabel.isHidden = true
            noDataImage.isHidden = true
            tableView.backgroundView  = nil
            return allData.count
        }

    }

x
Like what we are doing? Join Us! Become a contributor at iOS Pakistan.