Header 在 CollectionView 中未显示 iOS Swift
Header in CollectionView not Displaying iOS Swift
我想向 Collection 视图的 header 添加几个按钮。从情节提要中启用 'Section Header'。然后拖一个'view'到那个header。并将其背景颜色设置为绿色
但我不明白为什么它不显示。在模拟器中如您所见,只有一个空白的 space 为 header。
使用这个方法
在CollectionHeaderCell
中输入名字
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader:
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Header", for: indexPath as IndexPath)
headerView.backgroundColor = UIColor.blue;
return headerView
case UICollectionElementKindSectionFooter:
let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Footer", for: indexPath as IndexPath)
footerView.backgroundColor = UIColor.green;
return footerView
default:
assert(false, "Unexpected element kind")
}
}
//为每个单元格索引路径创建一个单元格
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("InviteFriendCell", forIndexPath: indexPath)
let profileimage: UIImageView = (cell.viewWithTag(5) as! UIImageView)
profileimage.image = UIImage(named:arrayofdata[indexPath.row]["image"]!)
return cell
}
我想向 Collection 视图的 header 添加几个按钮。从情节提要中启用 'Section Header'。然后拖一个'view'到那个header。并将其背景颜色设置为绿色
但我不明白为什么它不显示。在模拟器中如您所见,只有一个空白的 space 为 header。
使用这个方法
在CollectionHeaderCell
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader:
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Header", for: indexPath as IndexPath)
headerView.backgroundColor = UIColor.blue;
return headerView
case UICollectionElementKindSectionFooter:
let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Footer", for: indexPath as IndexPath)
footerView.backgroundColor = UIColor.green;
return footerView
default:
assert(false, "Unexpected element kind")
}
}
//为每个单元格索引路径创建一个单元格
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("InviteFriendCell", forIndexPath: indexPath)
let profileimage: UIImageView = (cell.viewWithTag(5) as! UIImageView)
profileimage.image = UIImage(named:arrayofdata[indexPath.row]["image"]!)
return cell
}