最近要研究下排布的游戲關卡界面的實現,簡單做了個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被選擇的事件處理
}
}
之后運行,你就可以看到效果啦。
