[IOS]swift自訂uicollectionviewcell

來源:互聯網
上載者:User

標籤: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的類裡面寫自己需要的代碼了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.