Jas*_*ges 12 uicollectionview uicollectionviewcell swift
UICollectionViewCell为我创建一个自定义UICollectionViewController,它通过注册笔尖来工作; 但是,没有按班级注册.
使用registerClass() - 失败
按类注册似乎是正确的 - 它构建,但在运行时抛出异常,从UIView中解开可选元素.没有引用插座,它运行; 但是,集合视图中不会出现单元格.
collectionView?.registerClass(MyCollectionViewCell.self,
forCellWithReuseIdentifier: "myCell")
Run Code Online (Sandbox Code Playgroud)
很明显,视图没有加载; 但是,我认为设置单元格的自定义类将提供必要的链接.
使用registerNib() - 工作
通过nib注册工作,这在显式加载视图时是有意义的.
let nib = UINib(nibName: "MyCollectionViewCell", bundle: nil)
collectionView?.registerNib(nib, forCellWithReuseIdentifier: "myCell")
Run Code Online (Sandbox Code Playgroud)
这里明确引用了视图,并为视图设置了自定义类; 然而,关于这一点似乎是错误的.
隔离示例项目中的问题,下面是要复制的视图和代码; 或者,这个项目可以在GitHub上找到.
Main.storyboard
我的主要故事板初始视图控制器是一个UICollectionViewController子类MyCollectionViewController:
MyCollectionViewController.swift
显示由笔尖和按类注册:
import UIKit
class MyCollectionViewController: UICollectionViewController {
var data = [String]()
override func viewDidLoad() {
super.viewDidLoad()
data = ["a", "b", "c"]
// This works, by nib
let nib = UINib(nibName: "MyCollectionViewCell", bundle: nil)
collectionView?.registerNib(nib, forCellWithReuseIdentifier: "myCell")
// This fails, by class
//collectionView?.registerClass(MyCollectionViewCell.self, forCellWithReuseIdentifier: "myCell")
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("myCell", forIndexPath: indexPath) as! MyCollectionViewCell
cell.title.text = data[indexPath.row]
return cell
}
}
Run Code Online (Sandbox Code Playgroud)
MyCollectionViewCell.xib
查看是UICollectionViewCell子类为MyCollectionViewCell具有UILabel:
在我的笔尖中,Collection Reusable View Identifier已设置为myCell:
MyCollectionViewCell.swift
定义类,并具有IBOutlet标签:
import UIKit
class MyCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var title: UILabel!
}
Run Code Online (Sandbox Code Playgroud)
使用nib,执行显示为:
为什么我不能UICollectionViewCell按班级注册?
同样,关于原型单元是否需要保留在主故事板集合视图控制器上,我有点模糊.在那里,我没有定义任何可重用的视图标识符.
| 归档时间: |
|
| 查看次数: |
12004 次 |
| 最近记录: |