Collection View提供了一个灵活方式展示集合视图,用法有点类似Table View
类.使用Collection view可以实现网格或者实现任何你能想象到的布局。在这篇教程中将实现自定义collection view cell,教程在iOS8&Xcode6下编译通过。
打开Xcode,新建项目选择Single View Application,Product Name填写IOS8SwiftCustomCollectionViewCellsTutorial,Organization Name和Organization Identifier自行填写,选择Swift语言与iPhone设备。
我们需要在自定义的Collection View Cell中展示一张图,点击这里下载图片并添加至工程
打开Storyboard,移除ViewController并拖拽 collection view Controller
至界面.由于我们移除了初始的ViewController,因此默认启动的界面没了,选中Table View Controller然后到Attribute Inspector控制面板勾选“Is Initial View Controller”选项,如下图:
选中Collection View同时打开Size Inspector面板,将Cell的大小设置为50x50
拖拽Image View至Collection View Cell中并确保高宽都为50,选中Image View并到Attribute Inspector选择Mode为“Aspect Fit”
现在Storyboard大致如下:
这时ViewController.swift
已经不需要了我们将它删除掉。接下来,在工程中新增一个文件,选择 iOS->Source->Cocoa Touch Class
,新建一个继承UICollectionViewController名为CollectionViewController类:
现在我们将新建的类与Storyboard的Collection View Controller 进行关联,打开Storyboard且选中Collection View Controller,然后到Identity Inspector控制面板改变Custrom Class为新建的类,如下图:
打开CollectionViewController.swift文件,在viewDidLoad方法中删除如下行
self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
打开Storyboard选中Collection View Cell设置Identifier为"Cell"
接下来创建Collection View Cell自定义class,在工程中新增一个文件,选择 iOS->Source->Cocoa Touch Class
,新建一个继承UICollectionViewCell名为CollectionViewCell
类
打开Storyboard选中CollectionViewCell设置自定的Class为CollectionViewCell
打开Assistant Editor并确保CollectionViewCell.swift 可见,Ctrl+Drag方式给ImageView创建如下Outlet
打开 CollectionViewController.swift 文件增加如下属性
var myImage = UIImage(named: "Apple_Swift_Logo")
改变如下代码:
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
// 1
// Return the number of sections
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// 2
// Return the number of items in the section
return 100
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
// 3
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as CollectionViewCell
// Configure the cell
cell.imageView.image = myImage
return cell
}
- 1.设置CollectionView的section数量为1
- 2.Collection View的cells数量为100
- 3.设置CollectionViewCelll的imageView为myimage
编译并运行项目,效果如下:
原文:http://www.ioscreator.com/tutorials/custom-collection-view-cell-tutorial-ios8-swift