標籤:style blog http color 使用 os io 檔案
剛剛接觸swift以及ios,不是很理解有的邏輯,導致某些問題。這裡分享一下swift自訂uicollectionviewcell
首先我的viewcontroller不是直接繼承uicollectionviewcontroller,而是添加的uicollectionview到我的storyboard,
然後再建立一個swift的檔案,讓這個swift繼承uicollectionviewcell
import Foundationclass SVGCell :UICollectionViewCell{ convenience required init(coder : NSCoder){ self.init(frame:CGRect(x: 0, y: 0, width: 50, height: 50)) } // required init(coder: NSCoder) {// fatalError("NSCoding not supported")// } override init(frame: CGRect) { super.init(frame: frame) }//about Inheritance //http://stackoverflow.com/questions/25126295/swift-class-does-not-implement-its-superclasss-required-members}
這裡繼承UICollectionViewCell的時候需要複寫 一個父類初始化方法,以及一個required的初始化方法,上面的一個連結是關於這個required的方法的一個說明,是新的版本所必須的,否則會報語法錯誤,錯誤內容大概是要求你實現一個required方法。
這裡不能夠寫一個自訂的初始化,因為這個cell不是因為init所建立的。
然後回到我們的viewcontroller
import UIKitclass ViewController: UIViewController ,UICollectionViewDataSource,UICollectionViewDelegate {//繼承後面這兩個協議,需要使用collectionview所必須的然後可以複寫下面的三個必須的方法 @IBOutlet weak var svgcollection: UICollectionView!
let reuseidentifier="SVGCell"
func collectionView(collectionView: UICollectionView!, numberOfItemsInSection section: Int) -> Int { return 2 }//這3個func在繼承了datasource & delegate一定要重寫,如果有多個tableview 或者collection view 則在裡面使用判斷,對參數collectionview判斷 func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell! { var cell:SVGCell=svgcollection.dequeueReusableCellWithReuseIdentifier(reuseidentifier, forIndexPath: indexPath) as SVGCell //reuse //這裡這個cell不需要初始化 //在return 之前 構造 一個cell 這裡如果再次初始化的話,會導致uncatch的exception,內容大概是沒有 reuseidentifier return cell }// func numberOfSectionsInCollectionView(collectionView: UICollectionView!) -> Int { return 1 }//}
在添加到我們的storyboard的uicollectionview的裡面
這個欄目裡面的cell設定它的屬性
設定好Identifier屬性就基本完成了,接下來可以在自訂的uiviewcollectionCell的類裡面寫自己需要的代碼了。