教你用CollectionView做一个炫酷的旋转轮

原文链接: UICollectionView Custom Layout Tutorial: A Spinning Wheel

本文翻译有部分改动,使用OC编写,原文使用的是Swift,如有需要,可以去原文下载Swift Demo,文章最后会提供OC的Demo。

开始

首先,去下载一个初始项目,原文是用的xib做了一个collectionView,我直接用代码编写了,最后得到的效果是这样:


环形布局

在项目里创建一个CircularCollectionViewLayout,像这样



因为这是UICollectionViewLayout的子类,而不是UICollectionViewFlowLayout的子类,所以你需要处理所有layout的相关操作。

在CircularCollectionViewLayout里,创建itemSize和radius属性

let itemSize = CGSize(width: 133, height: 173)

var radius: CGFloat = 500 {
  didSet {
    invalidateLayout()
  }
}

invalidateLayout的解释是:Call -invalidateLayout to indicate that the collection view needs to requery the layout information. 这里将该方法放在didset里,当radius属性改变时,你重新重新计算所有的属性进行布局。
在radius声明下面,定义一个anglePerItem

var anglePerItem: CGFloat {
  return atan(itemSize.width / radius)
}

这个属性可以任意变化,不过这个方法可以保证使其不会间隔太远。
接下来,重写collectionViewContentSize方法来确定你的collection view的内容大小

override func collectionViewContentSize() -> CGSize {
  return CGSize(width: CGFloat(collectionView!.numberOfItemsInSection(0)) * itemSize.width, height: CGRectGetHeight(collectionView!.bounds))
}

contentSize的高度应该和你的collectionView的高度一样,而宽度应该为 itemSize.width * numberOfItems。
现在,你还需要去把你的CollectionView的layout设置为CircularCollectionViewLayout。

自定义Layout Attributes

你需要自定义一个layout attributes继承自UICollectionViewLayoutAttributes来存储angular position 和 anchorPoint属性。
在CircularCollectionViewLayout文件里,该类的定义上面,添加一下代码

class CircularCollectionViewLayoutAttributes: UICollectionViewLayoutAttributes {
  // 1
  var anchorPoint = CGPoint(x: 0.5, y: 0.5)
  var angle: CGFloat = 0 {
    // 2 
    didSet {
      zIndex = Int(angle * 1000000)
      transform = CGAffineTransformMakeRotation(angle)
    }
  }
  // 3
  override func copyWithZone(zone: NSZone) -> AnyObject {
    let copiedAttributes: CircularCollectionViewLayoutAttributes = 
        super.copyWithZone(zone) as! CircularCollectionViewLayoutAttributes
    copiedAttributes.anchorPoint = self.anchorPoint
    copiedAttributes.angle = self.angle
    return copiedAttributes
  }
}
  1. 你需要一个anchorPoint属性因为旋转不是围绕着item的中心点来的。
  2. 在设定angle属性时,设置transform为旋转,参数为angle radians。同时,你需要将右边的item叠在左边的item上,所以你设置了zIndex根据angle增大而增大。
  3. 最后,你需要重写copyWithZone方法,这样当你在copy该属性时,会将你自定义的两个属性也copy进去。
    现在,回到CircularCollectionViewLayout 类,编写layoutAttributesClass方法
override class func layoutAttributesClass() -> AnyClass {
  return CircularCollectionViewLayoutAttributes.self
}

这个方法将告知collectionView使用你自己创建的layoutAttributes类而不是默认的UICollectionViewLayoutAttributes。
为了保存所有的layout attributes的实例,创建一个数组attributesList在CircularCollectionViewLayout里

var attributesList = [CircularCollectionViewLayoutAttributes]()

准备Layout

当collectionView第一次显示在屏幕上时,UICollectionViewLayout会执行prepareLayout方法。这个方法在你调用invalidateLayout时也会执行。
这也是layout过程中最重要的部分,因为这是你创建和保存所有layout attributes的地方。

override func prepareLayout() {
  super.prepareLayout()
  
  let centerX = collectionView!.contentOffset.x + (CGRectGetWidth(collectionView!.bounds) / 2.0)
  attributesList = (0..<collectionView!.numberOfItemsInSection(0)).map { (i) 
      -> CircularCollectionViewLayoutAttributes in
    // 1
    let attributes = CircularCollectionViewLayoutAttributes(forCellWithIndexPath: NSIndexPath(forItem: I,
        inSection: 0))
    attributes.size = self.itemSize
    // 2
    attributes.center = CGPoint(x: centerX, y: CGRectGetMidY(self.collectionView!.bounds))
    // 3
    attributes.angle = self.anglePerItem*CGFloat(i)
    return attributes
  }
}

简单点说,你对每个index path下的item做了一次遍历,然后:

  1. 为每个index path创建CircularCollectionviewLayoutAttributes, 并设置它的大小。
  2. 将每个item都放在屏幕中央。
  3. 根据anglePerItem * I,将所有item旋转。
    此外,你还需要重写下面这些方法。并且这些方法将经常被执行,所以要注意它们的效率。
override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
  return attributesList
}

override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
  return attributesList[indexPath.row]
}

运行程序,你会发现得到了一个这样子的collectionView


Anchor Point

回到prepareLayout方法,在centerX定义下面,加上

let anchorPointY = ((itemSize.height / 2.0) + radius) / itemSize.height

然后在map闭包里,return前,加上

attributes.anchorPoint = CGPoint(x: 0.5, y: anchorPointY)

然后在CircularCollectionViewCell里,重写applyLayoutAttributes方法

override func applyLayoutAttributes(layoutAttributes: UICollectionViewLayoutAttributes!) {
  super.applyLayoutAttributes(layoutAttributes)
  let circularlayoutAttributes = layoutAttributes as! CircularCollectionViewLayoutAttributes
  self.layer.anchorPoint = circularlayoutAttributes.anchorPoint
  self.center.y += (circularlayoutAttributes.anchorPoint.y - 0.5) * CGRectGetHeight(self.bounds)
}

这里,你用父类的方法来提供center,transform等等哪些默认已有的属性,而自定义的属性achorPoint需要我们自己手动作用在cell上。
再运行之后,


修复滚动效果

回到CircularCollectionViewLayout,然后在类的底部加上

override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
  return true
}

这里返回true来告诉collectionView,每当滚动时,就重新计算layout,这也会调用prepareLayout方法。
下面,添加几个参数

var angleAtExtreme: CGFloat {
  return collectionView!.numberOfItemsInSection(0) > 0 ? 
    -CGFloat(collectionView!.numberOfItemsInSection(0) - 1) * anglePerItem : 0
}
var angle: CGFloat {
  return angleAtExtreme * collectionView!.contentOffset.x / (collectionViewContentSize().width - 
    CGRectGetWidth(collectionView!.bounds))
}

然后在prepareLayout里,将这句

attributes.angle = (self.anglePerItem * CGFloat(i))

替换成

attributes.angle = self.angle + (self.anglePerItem * CGFloat(i))

这句代码将angle添加给了每个item,再运行你会发现,已经成功啦。


优化

在prepareLayout里,你给每个item都创建了attributes,但是并不是每个都显示在了屏幕里,其实那些没有显示出来的item,你完全可以跳过计算。
添加下面这段代码到prepareLayout方法的anchorPointY定义下面

// 1 
let theta = atan2(CGRectGetWidth(collectionView!.bounds) / 2.0, 
    radius + (itemSize.height / 2.0) - (CGRectGetHeight(collectionView!.bounds) / 2.0))
// 2
var startIndex = 0
var endIndex = collectionView!.numberOfItemsInSection(0) - 1 
// 3
if (angle < -theta) {
  startIndex = Int(floor((-theta - angle) / anglePerItem))
}
// 4
endIndex = min(endIndex, Int(ceil((theta - angle) / anglePerItem)))
// 5
if (endIndex < startIndex) {
  endIndex = 0
  startIndex = 0
}

你可以在原文看到这个算法是如何判定哪些item在屏幕内的。
当你知道了这些以后,你需要在prepareLayout方法里将

attributesList = (0..<collectionView!.numberOfItemsInSection(0)).map { (i) 
    -> CircularCollectionViewLayoutAttributes in

替换成

attributesList = (startIndex...endIndex).map { (i) 
    -> CircularCollectionViewLayoutAttributes in

然后就大功告成啦!!!

最后附上我改写的OC项目的链接: CircleCollectionViewDemo

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容