use*_*610 4 ios uicollectionview swift
正如标题所述,我在UICollectionReusableView中有一个标签.我使用的视图使用以下代码成功出列:
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let hourCell = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier:"Hour", forIndexPath: indexPath) as! HourCollectionReuseableView;
let time = String(indexPath.item) + "H";
hourCell.setTime(time);
return hourCell;
}
Run Code Online (Sandbox Code Playgroud)
这是接口构建器视图HourCollectionReuseableView.我在这里注意到我在文件所有者的自定义类中执行此操作:
这是收集重用标识符:
这是HourCollectionReuseableView班级:
class HourCollectionReuseableView: UICollectionReusableView {
@IBOutlet weak var hourLabel: UILabel!
@IBOutlet weak var hourDividerLine: UIView!
override func awakeFromNib() {
super.awakeFromNib();
}
func setTime(time:String) {
self.hourLabel.text = time;
}
Run Code Online (Sandbox Code Playgroud)
在我的视图控制器中,我按如下方式注册该类:
override func viewDidLoad() {
super.viewDidLoad();
self.collectionView.registerClass(HourCollectionReuseableView.self, forSupplementaryViewOfKind: "Hour", withReuseIdentifier:"Hour");
}
Run Code Online (Sandbox Code Playgroud)
代码不断崩溃self.hourLabel.text = time,出现以下错误:
致命错误:在展开Optional值时意外发现nil
我哪里错了?
正如@firstinq指出的那样,当你在使用a .xib时HourCollectionReuseableView,你应该尝试使用registerNib而不是registerClass.
所以,你的代码看起来应该更像
override func viewDidLoad() {
super.viewDidLoad();
self.collectionView.registerNib(UINib(nibName: "HourCollectionReuseableView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Hour");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1132 次 |
| 最近记录: |