我正在开发一个项目,其中使用 UICollectionView 和组合布局。我正在尝试将圆角半径添加到 UICollectionView 的部分标题中。我正在使用 UICollectionViewCompositionalLayout 创建部分,并且我希望每个部分标题具有不同的角半径、颜色和设计。
这是我的代码示例:
// Creating the compositional layout
let layout = UICollectionViewCompositionalLayout { sectionIndex, layoutEnvironment in
// configuring sections and items
}
// Registering section header
let headerRegistration = UICollectionView.SupplementaryRegistration
<HeaderCollectionViewCell>(elementKind: UICollectionView.elementKindSectionHeader) {
supplementaryView, string, indexPath in
// configuring header view
}
collectionView.collectionViewLayout = layout
collectionView.register(HeaderCollectionViewCell.self,
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: "HeaderCollectionViewCell")
如何使用 UICollectionViewCompositionalLayout 为 UICollectionView 的每个部分标题添加不同的角半径、颜色和设计?对此问题的任何帮助或指导将不胜感激。谢谢!
我尝试通过在部分内创建装饰器来装饰它,但似乎我只能更改颜色而不能更改角半径。此外,我添加的颜色不遵守部分限制。例如,如果我向某个部分添加水平填充,则该部分颜色会溢出到该填充之外并扩展到屏幕的宽度
您可以在注册区进行此操作。
例如:
let headerRegistration = UICollectionView.SupplementaryRegistration
<TitleSupplementaryView>(elementKind: CompColumnsVC.sectionHeaderElementKind) {
(supplementaryView, string, indexPath) in
supplementaryView.label.text = "\(string) for section \(indexPath.section)"
// default background color / corner radius /
// text color / border color / border width
supplementaryView.backgroundColor = .lightGray
supplementaryView.layer.cornerRadius = 0.0
supplementaryView.layer.borderColor = UIColor.black.cgColor
supplementaryView.layer.borderWidth = 1.0
supplementaryView.label.textColor = .black
// specific background color / corner radius /
// text color / border color / border width
// for sections 0, 1, 2 (all the rest use default
switch indexPath.section {
case 0:
supplementaryView.backgroundColor = .cyan
supplementaryView.layer.cornerRadius = 6.0
case 1:
supplementaryView.backgroundColor = .systemBlue
supplementaryView.label.textColor = .white
supplementaryView.layer.cornerRadius = 12.0
case 2:
supplementaryView.backgroundColor = .yellow
supplementaryView.layer.cornerRadius = 16.0
supplementaryView.layer.borderWidth = 0.0
supplementaryView.layer.borderColor = UIColor.red.cgColor
default:
()
}
}
给了我这个结果: