Swift UICollectionView 簡單使用

來源:互聯網
上載者:User

標籤:

最近要研究下排布的遊戲關卡介面的實現,簡單做了個UICollectionView的demo。

先看最後的效果:

 

下面來看實現的方法把,在Storyboard對應的ViewController中增加一個UICollectionView控制項,然後再其中加入一個CollectionViewCell


在其中增加一個Label控制項

 

注意,下面對這個Cell進行命名,命名成defaultCell, 這樣我們UI層面的工作就結束了。

 

代碼部分:

首先我們需要瞭解兩個類,UICollectionViewDataSource和UICollectionViewDelegate
UICollectionViewDataSource負責提供提供View所需要的資料來源
UICollectionViewDelegate負責處理View對應的各種事件

 

class MyCollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate{        @IBOutlet weak var cv: UICollectionView!        override func viewDidLoad() {        super.viewDidLoad()        cv.dataSource = self        cv.delegate = self    }            override func didReceiveMemoryWarning() {        super.didReceiveMemoryWarning()        // Dispose of any resources that can be recreated.    }    //實現UICollectionViewDataSource    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int    {//返回記錄數        return 100;    }      //實現UICollectionViewDataSource    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell    {//返回Cell內容,這裡我們使用剛剛建立的defaultCell作為顯示內容        var cell:MyColletionCell  = cv.dequeueReusableCellWithReuseIdentifier("defaultCell", forIndexPath: indexPath) as! MyColletionCell        cell.label.text = "\(indexPath.section):\(indexPath.row)"        return cell;    }        //實現UICollectionViewDataSource    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)    {        //某個Cell被選擇的事件處理    }}

 之後運行,你就可以看到效果啦。

Swift UICollectionView 簡單使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.