Skip to content

Instantly share code, notes, and snippets.

@pranjalsatija
Created February 8, 2020 00:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pranjalsatija/e774a5524720b431e7d17d0c11646ec9 to your computer and use it in GitHub Desktop.
Save pranjalsatija/e774a5524720b431e7d17d0c11646ec9 to your computer and use it in GitHub Desktop.
A reusable table view cell. Storyboard not included.
import UIKit
class ReusableTableViewCell: UITableViewCell {
static let identifier = String(describing: ReusableTableViewCell.self)
var leading: UIView? {
didSet {
if let oldValue = oldValue {
stackView.removeArrangedSubview(oldValue)
}
leading.map { stackView.insertArrangedSubview($0, at: 0) }
}
}
var trailing: UIView? {
didSet {
if let oldValue = oldValue {
stackView.removeArrangedSubview(oldValue)
}
trailing.map(stackView.addArrangedSubview)
}
}
var title: String? {
get { titleLabel?.text }
set {
titleLabel?.text = newValue
configureFonts()
}
}
var subtitle: String? {
get { subtitleLabel?.text }
set {
subtitleLabel?.text = newValue
configureFonts()
}
}
@IBOutlet private(set) var titleLabel: UILabel?
@IBOutlet private(set) var subtitleLabel: UILabel?
@IBOutlet private var stackView: UIStackView!
static func dequeue(in tableView: UITableView) -> Self {
tableView.register(UINib(nibName: identifier, bundle: .main), forCellReuseIdentifier: identifier)
let cell = tableView.dequeueReusableCell(withIdentifier: identifier) as! Self
cell.prepareForReuse()
return cell
}
override func prepareForReuse() {
super.prepareForReuse()
leading = nil
trailing = nil
title = nil
subtitle = nil
}
private func configureFonts() {
if title != nil && subtitle != nil {
titleLabel?.font = .preferredFont(forTextStyle: .headline)
subtitleLabel?.font = .preferredFont(forTextStyle: .subheadline)
} else if title != nil {
titleLabel?.font = .preferredFont(forTextStyle: .body)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment