【发布时间】:2016-02-12 22:24:54
【问题描述】:
首先我应该说我对 swift 还很陌生。我试图让我的视图控制器尽可能干净。 我创建了以下类
class AlbumArtist: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegate {
var musicLib = musicLibrary()
var albumCollection: UICollectionView!
var layout: CustomCollectionViewFlow!
init(albumCView: UICollectionView){
let nib = UINib(nibName: "CollectionViewCell", bundle: nil)
albumCollection = albumCView
musicLib.loadAlbums()
layout = CustomCollectionViewFlow()
print(layout)
super.init(frame: albumCollection.frame, collectionViewLayout: layout)
albumCollection.registerNib(nib, forCellWithReuseIdentifier: "item")
}
required init?(coder: NSCoder) {
musicLib.loadAlbums()
layout = CustomCollectionViewFlow()
super.init(coder: coder)
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return musicLib.getAlbumsCount()
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: CollectionViewCell = albumCollection.dequeueReusableCellWithReuseIdentifier("item", forIndexPath: indexPath) as! CollectionViewCell
let objects = musicLib.getAlbums().objectAtIndex(indexPath.item) as! MPMediaItemCollection
let repObjects = objects.representativeItem
cell.lbl_Name.text = repObjects!.valueForProperty(MPMediaItemPropertyAlbumTitle) as? String
let artwork = repObjects!.valueForProperty(MPMediaItemPropertyArtwork)
let artworkImage = artwork?.imageWithSize(CGSize(width: 230, height: 230))
if(artworkImage != nil){
cell.img_artwork.image = artworkImage
}
else{
cell.img_artwork.image = UIImage(named: "no_Artwork.png")
}
return cell
}
}
但是,我的 init 方法出现错误。必须调用超类'UICollectionView'的指定初始化器
我不确定我所做的是否正确我找不到任何关于如何做到这一点的示例。因此,如果我完全错了,我很想听听我需要做什么。
编辑:我更新了我的代码,它现在正在运行。然而,它永远不会涉及委托方法,因此永远不会填充集合视图。我用新代码更新了帖子中的代码。 在我的 viewController 中,我在 viewDidLoad 中像这样调用上面的类
AlbumArtist(albumCView: AlbumCollectionView)
我不确定我所做的是否正确
【问题讨论】:
-
⌥-点击
UICollectionView,滚动到底部并点击UICollectionView Class Reference。寻找指定的初始化器并实现它。 -
@vadian 我现在清理了初始化,但它从未到达委托方法。任何线索为什么以及如何解决这个问题?
-
您需要在 UI 和您的类之间建立连接,无论是在 Interface Builder 中还是通过以编程方式添加视图
-
界面生成器中的@vadian 我已将集合视图类设置为 AlbumArtist 类。它不起作用,所以我不确定我还能做些什么来使它起作用。我还尝试像这样
let ala = AlbumArtist(albumCView: AlbumCollectionView) AlbumCollectionView.delegate = ala在我的视图控制器中设置委托 -
如果collection view是在Interface Builder中设计的,将
Identify Inspector中的类设置为AlbumArtist,删除所有init方法,把你在init中做的东西放在viewDidLoad中。但基本上以这种方式继承UICollectionView是完全错误的。您需要一个带有UICollectionView插座的视图控制器,如维克多的回答中所述。
标签: ios swift uicollectionview