之前写过OC版本的标签布局,在自定义标签布局中可以查看,下面介绍swift版本的标签布局
和OC版一样,同样是自定义layout布局方式,主要代码如下:
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let attrs = UICollectionViewLayoutAttributes(forCellWith: indexPath)
let width = layoutDelegate?.itemWidth(layout: self, indexpath: indexPath)
let height = layoutDelegate?.itemHeight(layout: self, indexpath: indexPath)
var x:CGFloat = 0
var y:CGFloat = 0
var leftMargin:CGFloat = 0
var rowMargin:CGFloat = 0
var columnMargin:CGFloat = 0
if let delegate = layoutDelegate {
if delegate.responds(to: #selector(YGLayoutDelegate.itemEdgeInset(layout:))) {
leftMargin = delegate.itemEdgeInset!(layout: self).left
}else {
leftMargin = defaultEdgeInset.left
}
if delegate.responds(to: #selector(YGLayoutDelegate.itemRowMargin(layout:))) {
rowMargin = delegate.itemRowMargin!(layout: self)
}else {
rowMargin = defaultRowMargin
}
if delegate.responds(to: #selector(YGLayoutDelegate.itemColumnMargin(layout:))) {
columnMargin = delegate.itemColumnMargin!(layout: self)
}else {
columnMargin = defaultCoumnMargin
}
}
if maxX + width! + leftMargin > (collectionView?.frame.size.width)! {
maxX = leftMargin
x = maxX
maxY = rowMargin + maxY + height!
y = maxY
maxX = maxX + width! + columnMargin
}else {
x = maxX
y = maxY
maxX = maxX + width! + columnMargin
}
attrs.frame = CGRect(x: x, y: y, width: width!, height: height!)
var newFrame = collectionView?.frame
newFrame?.size.height = maxY + height! + rowMargin
collectionView?.frame = newFrame!
return attrs
}
代理方法的定义如下:
@objc protocol YGLayoutDelegate:NSObjectProtocol {
func itemWidth(layout:YGLayout,indexpath:IndexPath) -> CGFloat
func itemHeight(layout:YGLayout,indexpath:IndexPath) -> CGFloat
@objc optional func itemRowMargin(layout:YGLayout) -> CGFloat
@objc optional func itemColumnMargin(layout:YGLayout) -> CGFloat
@objc optional func itemEdgeInset(layout:YGLayout) -> UIEdgeInsets
}
外界调用只需要完成下面的方法:
func itemWidth(layout: YGLayout, indexpath: IndexPath) -> CGFloat {
let model = dataSource[indexpath.item]
return model.getItemSize().width
}
func itemHeight(layout: YGLayout, indexpath: IndexPath) -> CGFloat {
let model = dataSource[indexpath.item]
return model.getItemSize().height
}
func itemRowMargin(layout: YGLayout) -> CGFloat {
return scaleToWidth(size: 20)
}
func itemColumnMargin(layout: YGLayout) -> CGFloat {
return scaleToHeight(size: 20)
}
具体源码可以到我的github上查看
网友评论