Created
February 8, 2020 00:31
-
-
Save pranjalsatija/e774a5524720b431e7d17d0c11646ec9 to your computer and use it in GitHub Desktop.
A reusable table view cell. Storyboard not included.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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