📅  最后修改于: 2023-12-03 15:37:35.058000             🧑  作者: Mango
在CollectionView中,指示线是用于标识当前选中的item的。默认情况下,指示线的颜色和CollectionView的tintColor一致。但是,我们可以通过代码来自定义指示线的颜色。
找到CollectionView的属性showsHorizontalScrollIndicator和showsVerticalScrollIndicator,分别设置为false,这样就能看到指示线了。
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
在CollectionView的代理方法中,实现willDisplaySupplementaryView方法,获取到UICollectionViewLayoutAttributes对象,然后通过判断是指示线的kind来对其进行自定义颜色。
func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) {
if elementKind == UICollectionView.elementKindSectionFooter {
view.tintColor = UIColor.red // 自定义指示线的颜色
}
}
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// 隐藏默认的指示线
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
// 注册cell和footer
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "footer")
collectionView.delegate = self
collectionView.dataSource = self
}
// 返回item数量
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
// 配置cell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
cell.backgroundColor = UIColor.green
return cell
}
// 配置footer
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "footer", for: indexPath)
return footer
}
// 配置footer的大小
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return CGSize(width: collectionView.bounds.width, height: 2) // 设置高度为2,即为指示线的高度
}
// 配置指示线的颜色
func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) {
if elementKind == UICollectionView.elementKindSectionFooter {
view.tintColor = UIColor.red // 设置指示线的颜色
}
}
}
以上就是在CollectionView中自定义指示线颜色的方法。