如何使
swift中的标题和页脚在集合视图中?
我试图将标题和页脚组合在一起,但它仍然崩溃,我找不到迅速的教程来了解它.
我不怎么回复补充意见,而不只是一个.
我把它们都放在故事板上(类标识符)
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
//#warning Incomplete method implementation -- Return the number of sections
return 2
}
override func collectionView(collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int {
//#warning Incomplete method implementation -- Return the number of items in the section
return 10
}
override func collectionView(collectionView: UICollectionView,viewForSupplementaryElementOfKind kind: String,atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
var header: headerCell!
var footer: footerCell!
if kind == UICollectionElementKindSectionHeader {
header =
collectionView.dequeueReusableSupplementaryViewOfKind(kind,withReuseIdentifier: "header",forIndexPath: indexPath)
as? headerCell
}
return header
}
Error:
UICollectionElementKindCell with identifier one – must register a nib or a class for the identifier or connect a prototype cell in a storyboard’
override func collectionView(collectionView: UICollectionView,cellForItemAtIndexPath indexPath: NSIndexPath) -> profileCC {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("one",forIndexPath: indexPath) as! profileCC
// Configure the cell
return cell
}
override func collectionView(collectionView: UICollectionView,atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader:
let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind,forIndexPath: indexPath) as! headerCell
headerView.backgroundColor = UIColor.blueColor();
return headerView
case UICollectionElementKindSectionFooter:
let footerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind,withReuseIdentifier: "footer",forIndexPath: indexPath) as! footerCell
footerView.backgroundColor = UIColor.greenColor();
return footerView
default:
assert(false,"Unexpected element kind")
}
}
我希望有人会帮忙.
解决方法
您可以使UICollectionViewController处理UICollectionView,并在Interface Builder中激活页脚和页眉部分,然后可以使用以下方法预览UICollectionView添加的两个部分:
override func collectionView(collectionView: UICollectionView,withReuseIdentifier: "Header",forIndexPath: indexPath) as! UICollectionReusableView
headerView.backgroundColor = UIColor.blueColor();
return headerView
case UICollectionElementKindSectionFooter:
let footerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind,withReuseIdentifier: "Footer",forIndexPath: indexPath) as! UICollectionReusableView
footerView.backgroundColor = UIColor.greenColor();
return footerView
default:
assert(false,"Unexpected element kind")
}
}
在上面的代码中,我将页脚和标题的标识符作为页眉和页脚为例,你可以按照要求进行操作.如果要创建自定义页眉或页脚,则需要为每个页面创建一个UICollectionReusableView子类,并根据需要进行自定义.
您可以在Interface Builder中或以下列方式在代码中注册自定义页脚和标题类:
registerClass(myFooterViewClass,forSupplementaryViewOfKind: UICollectionElementKindSectionFooter,withReuseIdentifier: "myFooterView")