Last active
December 26, 2018 08:42
-
-
Save nathantannar4/d46bcd5675bc40ada45e686ec6d0ee59 to your computer and use it in GitHub Desktop.
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 | |
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