Skip to content

Instantly share code, notes, and snippets.

@freemansion
Created November 12, 2018 06:23
Show Gist options
  • Save freemansion/2b0fa21dfc563d8315ae48c92fa70456 to your computer and use it in GitHub Desktop.
Save freemansion/2b0fa21dfc563d8315ae48c92fa70456 to your computer and use it in GitHub Desktop.
UITableView hide empty rows example
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let dataSource: [String] = [Int](0..<8).map { "Cell #\($0+1)" }
var tableView: UITableView?
static let cellIdentifier = "TableViewCellIdentifier"
override func viewDidLoad() {
super.viewDidLoad()
let tableView = UITableView(frame: view.bounds)
view.addSubview(tableView)
let constraints = [
tableView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0),
tableView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0),
tableView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0)
]
NSLayoutConstraint.activate(constraints)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: ViewController.cellIdentifier)
tableView.dataSource = self
tableView.delegate = self
tableView.isEmptyRowsHidden = true
self.tableView = tableView
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: ViewController.cellIdentifier, for: indexPath)
cell.textLabel?.text = dataSource[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
tableView.isEmptyRowsHidden = !tableView.isEmptyRowsHidden
tableView.layoutIfNeeded()
}
}
extension UITableView {
@IBInspectable
var isEmptyRowsHidden: Bool {
get {
return tableFooterView != nil
}
set {
if newValue {
tableFooterView = UIView(frame: .zero)
} else {
tableFooterView = nil
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment