IOS开发之CollectionView的使用
collectionview是IOS8之后添加的新的组件,和tableview一样的功能,据说比后者更容易使用。因为没有研究里面生层次的实现方式,因此这一点不做评价,这里仅仅是讲collectionview的使用方法。
使用CollectionView需要实现UICollectionViewDataSource和UICollectionViewDelegate这两个协议,实现这两个协议需要重写两个方法:
第一个:用来返回collectionViewCell的数量
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
//返回记录数
return 23
}
第二个:用来设置cell的样式
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
// 获取设计的单元格,不需要再动态添加界面元素
let cell = (collectionView.dequeueReusableCellWithReuseIdentifier("cellName", forIndexPath: indexPath)) as UICollectionViewCell
return cell
}
现在不需要在动态设置Cell的样式了,可以在storyboard中的设置,然后设置Cell的 identifier为"cellName",通过
collectionView.dequeueReusableCellWithReuseIdentifier
使用collectionview有两个方法一个是直接在storyboard中新建一个UICollectionViewController,还有一个方法是新建一个普通的UIViewController,然后让其继承UICollectionViewDataSource和UICollectionViewDelegate,然后在这个类中实现上面的两个方法。
这样就可以使用了。
如果collectionviewcell中有其他的组件,想在这里设置需要使用viewWithTag这个方法。使用这个方法需要先对view组件设置Tag,然后通过viewWithTag(),来获取然后在根据自己的意愿来设置这个view。