其實這個案例還有一些問題沒有解決,但是這個案例里面有許多值得分享的知識點和坑,我來一一列舉一下,以后會完善一下這個案例
CollectionView的實現##
Collection view的大部分設置我都是在StoryBoard中完成,但是在實際開發中,我們通常會將TableView和CollectionView 的實現作為控制器的擴展寫到另外一個類中,但是特別要注意的是,Swift3.0中貌似要求,控制器中使用到的類別中的方法必須是公共方法,同樣的在類別中使用到的控制器中的屬性也不允許是私有的。下面來看一下它的用法
extension ViewController : UICollectionViewDataSource {
private func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return interests.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "InterestCell", for: indexPath) as! ImgCollectionViewCell
cell.interest = self.interests[indexPath.item]
return cell
}
}
Static Func###
其實之前一直是有疑問的,之前OC中的類方法在Swift中如何實現,實際上在這里,我們就是通過靜態方法Static Func類實現的在本例中,我們還學到了如何在犯法中返回一個數組,代碼片段如下
static func createInterests() -> [Interest]
{
return [
Interest(featuredImage: UIImage(named: "hello")!),
Interest( featuredImage: UIImage(named: "dudu")!),
Interest(featuredImage: UIImage(named: "bodyline")!),
Interest(featuredImage: UIImage(named: "wave")!),
Interest(featuredImage: UIImage(named: "darkvarder")!),
Interest(featuredImage: UIImage(named: "hhhhh")!),
]
}
另外,在使用UIImage(named: "wave")!這個房發的時候,我發現像往常那樣直接添加在工程根目錄下會找不到這個圖片,必須將圖片放置在Assets.xcassets下才能找到圖片,地址請戳