Swift3.0 創(chuàng)建UICollectionView

效果圖如下:


Simulator Screen Shot 2017年6月23日 下午3.56.36.png

請(qǐng)看如下代碼,cell是使用xib創(chuàng)建的:
<pre>
class SecondViewController: UIViewController , UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{

var collectionView:UICollectionView?
var dataArray = NSMutableArray()
var imageArray = NSMutableArray()


override func viewDidLoad() {
    super.viewDidLoad()
    self.dataArray = ["BIGBANG","G-DRAGON","TOP","DAESUNG","SEUNGRI","TAEYANG","MINO","BOBBY","B.I"]
    self.imageArray = ["bigbang","gd","top","daesung","seungri","taeyang","mino","bobby","bi"]

   createCCollectionView()

}
//創(chuàng)建collectionView
func createCCollectionView(){

    let flowLayout = UICollectionViewFlowLayout()
    collectionView = UICollectionView.init(frame:self.view.frame,collectionViewLayout:flowLayout)
    //item大小
    flowLayout.itemSize = CGSize(width:(self.view.frame.size.width/4),height:130)
    flowLayout.minimumLineSpacing = 0
    flowLayout.minimumInteritemSpacing = 0
    collectionView?.backgroundColor = UIColor.groupTableViewBackground
    collectionView?.delegate = self
    collectionView?.dataSource = self


    //注冊(cè)cell
    collectionView!.register(UINib (nibName: "XIBCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "XIBCollectionViewCell")
    self.view.addSubview(collectionView!)


}

</pre>
下面是collectionView的代理方法:
<pre>
//分區(qū)item個(gè)數(shù)
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dataArray.count
}

//定義cell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "XIBCollectionViewCell", for: indexPath)as!XIBCollectionViewCell
    cell.cellImage?.image = UIImage(named:self.imageArray[indexPath.row] as! String)
    cell.cellLabel!.text = self.dataArray[indexPath.row] as? String
    return cell

}

</pre>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫(kù)、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,346評(píng)論 4 61
  • 因?yàn)橐Y(jié)局swift3.0中引用snapKit的問(wèn)題,看到一篇介紹Xcode8,swift3變化的文章,覺(jué)得很詳細(xì)...
    uniapp閱讀 4,872評(píng)論 0 12
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,057評(píng)論 25 709
  • 開(kāi)檔,點(diǎn)餐具。是有多無(wú)聊。只有一個(gè)客人,服務(wù)員多過(guò)客人。 想去做銷售,因?yàn)橄肽酶叩墓べY。學(xué)習(xí),成長(zhǎng),鍛煉自己。發(fā)...
    bbd77fe72ff7閱讀 200評(píng)論 0 0
  • 王二丫0311閱讀 230評(píng)論 1 0

友情鏈接更多精彩內(nèi)容