SwiftUICollectionView简单使用
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
SwiftUICollectionView简单使⽤
最近要研究下排布的游戏关卡界⾯的实现,简单做了个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
bel.text = "\(indexPath.section):\(indexPath.row)"
return cell;
}
//实现UICollectionViewDataSource
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
//某个Cell被选择的事件处理
}
}
之后运⾏,你就可以看到效果啦。