Introducing, GenericCells!… Capitalizing on Swift's generics, we can get all the benefits of a custom UITableViewCell or UICollectionViewCell class, without the hassle of a new class for each of them.
Create a UIView subclass for the layout you want:
final class MyView: UIView {
let imageView: UIImageView
let titleLabel: UILabel
let subtitleLabel: UILabel
// And add more views to your heart's content
}
Register the cell with a UITableView or UICollectionView:
tableView.register(GenericTableCell<MyView>.self)
collectionView.register(GenericCollectionCell<MyView>.self)
Dequeue the cell with a UITableView or UICollectionView:
let cell = tableView.dequeueReusableCell(forIndexPath: indexPath) as GenericTableCell<MyView>
let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath) as GenericCollectionCell<MyView>
And customize it to your heart's content. The view you wish to access will be available via the .customView
property:
cell.customView.titleLabel.text = "This library rules!"
cell.customView.imageView.image = UIImage(named: "success")
Extra credit, let's add recycling support. Extend your view with the ReusableGenericView
protocol:
extension MyView: ReusableGenericView {
func prepareForReuse() {
self.titleLabel.text = ""
self.subtitleLabel.text = ""
self.imageView.image = nil
}
}
And it will get called when the cell is recycled.
You can use SPM to install GenericCells
.
You can also use CocoaPods to install GenericCells
by adding it to your Podfile
:
platform :ios, '9.0'
use_frameworks!
pod 'GenericCells'
Or install it manually by downloading GenericTableCell.swift
, GenericCollectionCell.swift
, and ReusableView.swift
, and dropping it in your project.
Hi, I'm Joe everywhere on the web, but especially on Twitter.
See the license for more information about how you can use GenericCells.
Yes, that's it. And if you don't like it, well sorry, here's a rainbow. 🌈