classDYOptionTagFlowLayout: UICollectionViewFlowLayout{ // item space 间距从外部传入或者写死. 用来计算是否换行时使用. privatelet listItemSpace: CGFloat=8 overrideinit() { super.init() } requiredinit?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } overridefuncprepare() { super.prepare() }
// MARK: - Define area to show and item count overridefunclayoutAttributesForElements(inrect: CGRect) -> [UICollectionViewLayoutAttributes]? { let superElementAttributes =super.layoutAttributesForElements(in: rect) let array =NSArray(array: superElementAttributes!, copyItems: true) let attributesToReturn = array as! [UICollectionViewLayoutAttributes] for attributes in attributesToReturn { ifnil== attributes.representedElementKind { let indexPath = attributes.indexPath attributes.frame =self.layoutAttributesForItem(at: indexPath)?.frame ?? .zero } } return attributesToReturn } // MARK: - Define cell layout overridefunclayoutAttributesForItem(atindexPath: IndexPath) -> UICollectionViewLayoutAttributes? { // System calculated attributes let currentItemAttributes =super.layoutAttributesForItem(at: indexPath)?.copy() as!UICollectionViewLayoutAttributes // Set inset let currentSystemFlowlayout =self.collectionView!.collectionViewLayout as!UICollectionViewFlowLayout let sectionInset = currentSystemFlowlayout.sectionInset // first item if indexPath.item ==0 { var frame = currentItemAttributes.frame frame.origin.x = sectionInset.left currentItemAttributes.frame = frame return currentItemAttributes } // Not first item, then need to get one before attributes' frame let previousIndexPath =NSIndexPath(item: indexPath.item -1, section: indexPath.section) let previousFrame =self.layoutAttributesForItem(at: previousIndexPath asIndexPath)?.frame // Previous and current item frame adjacent points let previousFrameRightPoint = previousFrame!.origin.x + previousFrame!.size.width +self.listItemSpace
// Current frame let currentFrame = currentItemAttributes.frame let strecthedCurrentFrame =CGRect(x: 0, y: currentFrame.origin.y, width: self.collectionView!.frame.size.width, height: currentFrame.size.height) // Two frame has same area. let intersect = previousFrame!.intersects(strecthedCurrentFrame) if!intersect { // Same line var frame = currentItemAttributes.frame frame.origin.x = sectionInset.left currentItemAttributes.frame = frame return currentItemAttributes } // Other line first item var frame = currentItemAttributes.frame frame.origin.x = previousFrameRightPoint currentItemAttributes.frame = frame return currentItemAttributes } }
// 以上代码, 粘贴复制即可使用.
注意📢
1 2
let array =NSArray(array: superElementAttributes!, copyItems: true) let attributesToReturn = array as! [UICollectionViewLayoutAttributes]