Ios UICollectionViewLayout:仅向特定单元格添加装饰视图
我开发了一个定制的CollectionViewLayout,它使用Ios UICollectionViewLayout:仅向特定单元格添加装饰视图,ios,uicollectionview,uicollectionviewlayout,uicollectionreusableview,uicollectionviewflowlayout,Ios,Uicollectionview,Uicollectionviewlayout,Uicollectionreusableview,Uicollectionviewflowlayout,我开发了一个定制的CollectionViewLayout,它使用DecorationView来显示单元格后面的阴影 但是,我只想在一些单元格中添加此装饰。UICollectionView是垂直的,但它可能在单元格内包含一个嵌入的水平的UICollectionView。如图所示,不应装饰带有嵌入式UICollectionView的单元格: 下面是我用来添加阴影的代码。UICollectionViewLayout没有提供检索单元格类的方法,因此它可以决定是否添加阴影: override fu
DecorationView
来显示单元格后面的阴影
但是,我只想在一些单元格中添加此装饰。UICollectionView
是垂直的,但它可能在单元格内包含一个嵌入的水平的UICollectionView
。如图所示,不应装饰带有嵌入式UICollectionView
的单元格:
下面是我用来添加阴影的代码。UICollectionViewLayout
没有提供检索单元格类的方法,因此它可以决定是否添加阴影:
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let parent = super.layoutAttributesForElements(in: rect)
guard let attributes = parent, !attributes.isEmpty else {
return parent
}
let sections = attributes.map{$0.indexPath.section}
let unique = Array(Set(sections))
// Need to detect, which sections contain an embedded UICollectionView and exclude them from the UNIQUE set
let backgroundShadowAttributes: [UICollectionViewLayoutAttributes] = unique.compactMap{ section in
let indexPath = IndexPath(item: 0, section: section)
return self.layoutAttributesForDecorationView(ofKind: backgroundViewClass.reuseIdentifier(),
at: indexPath)
}
return attributes + backgroundShadowAttributes + separators
}
有没有办法有条件地指定应该装饰哪些视图?完成此代码:
直接询问数据源是否为特定部分显示阴影的协议:
protocol SectionBackgroundFlowLayoutDataSource {
func shouldDisplayBackgroundFor(section: Int) -> Bool
}
并利用func layouttributesforements(在rect:CGRect中)
方法中的协议:
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let parent = super.layoutAttributesForElements(in: rect)
guard let attributes = parent, !attributes.isEmpty else {
return parent
}
attributes.forEach(configureRoundCornersAttributes)
// Display shadows for every section by default
var sectionsWithShadow = Set(attributes.map{$0.indexPath.section})
if let dataSource = collectionView?.dataSource as? SectionBackgroundFlowLayoutDataSource {
// Ask DataSource for sections with shadows, if it supports the protocol
sectionsWithShadow = sectionsWithShadow.filter{dataSource.shouldDisplayBackgroundFor(section: $0)}
}
let backgroundShadowAttributes: [UICollectionViewLayoutAttributes] = sectionsWithShadow.compactMap{ section in
let indexPath = IndexPath(item: 0, section: section)
return self.layoutAttributesForDecorationView(ofKind: backgroundViewClass.reuseIdentifier(),
at: indexPath)
}
return attributes + backgroundShadowAttributes + separators
}
func shouldldisplaybackgroundfor(section:Int)->Bool
的返回速度可能比cellForItemAtIndexPath
更快,因为它不需要完整的单元格配置。为什么不能使用阴影创建自定义单元格类并在UICollectionViewLayout中创建适当的填充?有更复杂的情况,当UICollectionView
看起来像UITableView
并且阴影渲染正确时。将阴影附加到UICollectionViewCell
在这种情况下不起作用: