Created
March 8, 2017 17:15
-
-
Save algal/f329075ada0947edc85972c2735cdc61 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
/** | |
Generic CollectionViewCell, which can be specialized to wrap a UIView. | |
To use this, you can simply define a typealias like so: | |
``` | |
class FooView : UIVIew { /* ... */ } | |
typealias FooCell = WrappedCollectionViewCell<FooView> | |
``` | |
The resulting `UICollectionViewCell` will hug the wrapped view | |
with layout constraints, so that the cell and the wrapped view can influence | |
each other's size via the normal Auto Layout mechanism. This allows either for | |
the layout object to specify the cell's `itemSize`, or for the cell to declare | |
its own size as a self-sizing cell, when the layout uses `estimatedItemSize`. | |
Known-good: Swift 3 | |
*/ | |
class WrappedCollectionViewCell<T:UIView> : UICollectionViewCell | |
{ | |
private func setup() | |
{ | |
let wrappedView = T.init(frame: self.contentView.bounds) | |
self.contentView.addSubview(wrappedView) | |
wrappedView.translatesAutoresizingMaskIntoConstraints = false | |
for vfl in ["V:|[v]|","H:|[v]|"] | |
{ | |
let cs = NSLayoutConstraint.constraints(withVisualFormat: vfl, options: [], metrics: nil, views: ["v":wrappedView]) | |
self.contentView.addConstraints(cs) | |
} | |
} | |
var wrappedView:T { | |
return self.contentView.subviews.first! as! T | |
} | |
class var classReuseIdentifier:String { | |
return T.description() + "CellIdentifier" | |
} | |
override class var requiresConstraintBasedLayout:Bool { return true } | |
override init(frame:CGRect) | |
{ | |
super.init(frame:frame) | |
setup() | |
} | |
required init?(coder aDecoder: NSCoder) { | |
super.init(coder:aDecoder) | |
setup() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment