Skip to content

Instantly share code, notes, and snippets.

@nathantannar4
Last active December 26, 2018 08:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathantannar4/d46bcd5675bc40ada45e686ec6d0ee59 to your computer and use it in GitHub Desktop.
Save nathantannar4/d46bcd5675bc40ada45e686ec6d0ee59 to your computer and use it in GitHub Desktop.
import UIKit
protocol IReusableView: AnyObject where Self: UIView {
func prepareForReuse()
}
class TableViewCell<ViewType: IReusableView>: UITableViewCell {
let wrappedView = ViewType()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
cellDidLoad()
}
override func prepareForReuse() {
super.prepareForReuse()
wrappedView.prepareForReuse()
}
func cellDidLoad() {
contentView.addSubview(wrappedView)
wrappedView.fillSuperview()
}
}
class CollectionViewCell<ViewType: IReusableView>: UICollectionViewCell {
let wrappedView: ViewType
override init(frame: CGRect) {
wrappedView = ViewType(frame: frame)
super.init(frame: frame)
cellDidLoad()
}
override func prepareForReuse() {
super.prepareForReuse()
wrappedView.prepareForReuse()
}
func cellDidLoad() {
contentView.addSubview(wrappedView)
wrappedView.fillSuperview()
}
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
setNeedsLayout()
layoutIfNeeded()
let size = contentView.systemLayoutSizeFitting(layoutAttributes.size)
var newFrame = layoutAttributes.frame
newFrame.size.height = ceil(size.height)
layoutAttributes.frame = newFrame
return layoutAttributes
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment