Skip to content

Instantly share code, notes, and snippets.

@SwapnanilDhol
Created August 1, 2020 12:15
Show Gist options
  • Save SwapnanilDhol/649bd2d4dd330bc902054e86a45114df to your computer and use it in GitHub Desktop.
Save SwapnanilDhol/649bd2d4dd330bc902054e86a45114df to your computer and use it in GitHub Desktop.
//
// UITableView+EmptyView.swift
// StickerTweet
//
// Created by Swapnanil Dhol on 7/6/20.
// Copyright © 2020 Swapnanil Dhol. All rights reserved.
//
import UIKit
extension UITableView {
func setEmptyView(title: String, message: String) {
let emptyView = UIView(frame: CGRect(x: self.center.x,
y: self.center.y,
width: self.bounds.size.width,
height: self.bounds.size.height))
let titleLabel = UILabel()
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.textColor = .label
titleLabel.font = .systemFont(ofSize: 18, weight: .bold)
titleLabel.text = title
titleLabel.numberOfLines = 0
titleLabel.textAlignment = .center
let messageLabel = UILabel()
messageLabel.translatesAutoresizingMaskIntoConstraints = false
messageLabel.textColor = .secondaryLabel
messageLabel.font = .systemFont(ofSize: 17, weight: .medium)
messageLabel.text = message
messageLabel.numberOfLines = 0
messageLabel.textAlignment = .center
emptyView.addSubview(titleLabel)
emptyView.addSubview(messageLabel)
NSLayoutConstraint.activate([
titleLabel.centerYAnchor.constraint(equalTo: emptyView.centerYAnchor),
titleLabel.centerXAnchor.constraint(equalTo: emptyView.centerXAnchor),
titleLabel.leadingAnchor.constraint(equalTo: emptyView.leadingAnchor, constant: 20),
titleLabel.trailingAnchor.constraint(equalTo: emptyView.trailingAnchor, constant: -20),
messageLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 10),
messageLabel.leadingAnchor.constraint(equalTo: emptyView.leadingAnchor, constant: 20),
messageLabel.trailingAnchor.constraint(equalTo: emptyView.trailingAnchor, constant: -20)
])
self.backgroundView = emptyView
self.separatorStyle = .none
}
func restore() {
self.backgroundView = nil
self.separatorStyle = .singleLine
}
}
//MARK: - Usage
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//This code uses the NSFRC from CoreData's stack introduced in iOS 13. The basic idea is to show the empty view
//when the array containing the elements is empty.
//Return the setEmptyView function right before returning 0
guard let sections = fetchedResultsController.sections else {
tableView.setEmptyView(title: "Saved Tweets and Notes will show up here.",
message: "Tap the + button to get started.")
return 0
}
let sectionInfo = sections[section]
if sectionInfo.numberOfObjects == 0 {
tableView.setEmptyView(title: "Saved Tweets and Notes will show up here.",
message: "Tap the + button to get started.")
} else {
tableView.restore()
}
return sectionInfo.numberOfObjects
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment