ios Swift 中 UICollectionView 的单元格 registerClass
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24110811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
UICollectionView's cell registerClass in Swift
提问by jarjar
Right now I'm using NSClassFromString
, but is there a better way to get an AnyClass
! from a class in Swift? I am trying to pass the reference to my collection view's -registerClass:forCellWithReuseIdentifier:
method.
现在我正在使用NSClassFromString
,但是有没有更好的方法来获得AnyClass
! 来自 Swift 的课程?我正在尝试将引用传递给我的集合视图的-registerClass:forCellWithReuseIdentifier:
方法。
collectionView.registerClass(NSClassFromString("MyCoolViewCell"), forCellWithReuseIdentifier: "MyCoolViewCell")
回答by Matthias Bauch
This is currently just a blind but educated guess, but using Class.self
might be what you want.
这目前只是一个盲目但有根据的猜测,但使用Class.self
可能是您想要的。
collectionView.registerClass(MyCoolViewCell.self, forCellWithReuseIdentifier: "MyCoolViewCell")
回答by atulkhatri
In case you are using a nib file, use this code instead:
如果您使用的是 nib 文件,请改用以下代码:
let nib = UINib(nibName: "MyCoolViewCell", bundle: nil)
collectionView?.register(nib, forCellWithReuseIdentifier: "MyCoolViewCellIdentifier")
回答by Maria Ortega
In Swift 3:
在 Swift 3 中:
self.collectionView.register(CustomCollectionViewCell.self, forCellWithReuseIdentifier: "CustomCollectionViewCellReuseIdentifier")
回答by yhlin
NSClassFromString("MyCoolViewCell")
might get nil.
Should add module name in prefix:collectionView.registerClass(NSClassFromString("MyApp.MyCoolViewCell"), forCellWithReuseIdentifier: "MyCoolViewCell")
NSClassFromString("MyCoolViewCell")
可能为零。
应该在前缀中添加模块名称:collectionView.registerClass(NSClassFromString("MyApp.MyCoolViewCell"), forCellWithReuseIdentifier: "MyCoolViewCell")
If cellClass not a variable, use MyCoolViewCell.self
is a better choice.
如果 cellClass 不是变量, useMyCoolViewCell.self
是更好的选择。