class TGCollectionView: UIView {
vardatas: [Int]? {
didSet{
guarddatas!=nilelse{
return
}
reloadDate()
}
}
var collectionView: UICollectionView?
override init(frame: CGRect) {
super.init(frame: frame)
letview =UICollectionView(frame:CGRect(x:0,y:0,width: frame.size.width,height: frame.size.height),collectionViewLayout:CollectionViewFlowLayout())
view.isPagingEnabled=true
view.dataSource=self
view.register(CollectionViewCell.classForCoder(),forCellWithReuseIdentifier:"CollectionViewCell")
view.backgroundColor = .orange
addSubview(view)
}
requiredinit?(coder:NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func reloadDate() {
guardletcollectionView =collectionViewelse{
return
}
collectionView.reloadData()
}
}
extension TGCollectionView: UICollectionViewDataSource {
funccollectionView(_collectionView:UICollectionView,numberOfItemsInSectionsection:Int) ->Int{
returndatas?.count??0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
letcell = collectionView.dequeueReusableCell(withReuseIdentifier:"CollectionViewCell",for: indexPath)
returncell
}
}
class CollectionViewFlowLayout: UICollectionViewFlowLayout {
override init() {
super.init()
scrollDirection = .horizontal
minimumLineSpacing = 0
minimumInteritemSpacing = 0
itemSize = CGSizeMake(100, 300)
}
requiredinit?(coder:NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class CollectionViewCell: UICollectionViewCell {
lazyvarview:UIView= {
letview =UIView()
view.backgroundColor = UIColor(red: CGFloat(arc4random()%255)/255.0, green: CGFloat(arc4random()%255)/255.0, blue: CGFloat(arc4random()%255)/255.0, alpha: 1.0)
returnview
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(view)
view.frame= frame
}
requiredinit?(coder:NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
网友评论