環(huán)形CollectionView的實現(xiàn)

Simulator Screen Shot Apr 17, 2017, 7.14.28 PM.png

同時根據(jù)不同數(shù)量的數(shù)據(jù)能夠自動生成正確size的圓:

Simulator Screen Shot Apr 17, 2017, 7.18.16 PM.png

基本思路還是利用CollectionViewLayout來客制化CollectionView的外觀郑什,既然如此,那么我們先創(chuàng)建一個Layout的subclass:

import UIKit

protocol CircularDelegateLayout {
    func collectionView(collectionView:UICollectionView, radiusForItemAtIndexPath indexPath:IndexPath) -> CGFloat
}

class CircularLayout: UICollectionViewLayout {
    //Well, I am not using delegate since I am control freak, however, you can customize radius if you want through protocol above.
    var delegate:CircularDelegateLayout!
    fileprivate var viewCenter:CGPoint!
    fileprivate var numberOfItems = 0
    fileprivate var centerCircleRadius:CGFloat!
    fileprivate var itemRadius:CGFloat!
    fileprivate var itemSize:CGSize!
    fileprivate var centerItemSize:CGSize!
    
    override var collectionViewContentSize: CGSize {
        return collectionView!.bounds.size
    }
    
    override func prepare() {
        super.prepare()
        guard let collectionView = collectionView else {return}
        //You only have one section, yes, only one
        numberOfItems = collectionView.numberOfItems(inSection: 0)
        viewCenter = CGPoint(x: collectionView.bounds.midX, y: collectionView.bounds.midY)
        let shortest = min(collectionView.bounds.width, collectionView.bounds.height)
        centerCircleRadius = shortest / 3.4
        
        //Why 7 is the magic number? Well, to be frankly, it's not, but I like 7, so I put it here.
        if numberOfItems > 7 {
            /*switch reader {
                case .EastAsian:
                    print("Ask your high school teacher to figure out why.")
                default:
                    print("Never mind, it's Voodoo, just use it.")
             }
             */
            itemRadius = CGFloat(2 * Double(centerCircleRadius) * sin(.pi / Double(numberOfItems - 1)))
        }else {
            itemRadius = centerCircleRadius
        }
        
        itemSize = CGSize(width: itemRadius, height: itemRadius)
        centerItemSize = CGSize(width: centerCircleRadius, height: centerCircleRadius)
    }
    
    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
        let angle = 2 * .pi * CGFloat(indexPath.item) / CGFloat(numberOfItems - 1)
        
        switch indexPath.item {
        case 0:
            attributes.center = viewCenter
            attributes.size = centerItemSize
        default:
            /*switch reader {
             case .EastAsian:
                print("Ask your high school teacher to figure out why.")
             default:
                print("Never mind, it's Voodoo, just use it.")
             }
             */
            attributes.center = CGPoint(x: viewCenter.x + centerCircleRadius * cos(angle), y: viewCenter.y + centerCircleRadius * sin(angle))
            attributes.size = itemSize
        }
        return attributes
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        guard let collectionView = collectionView else {return nil}
        return (0..<collectionView.numberOfItems(inSection: 0)).flatMap{ item -> UICollectionViewLayoutAttributes? in
            self.layoutAttributesForItem(at: IndexPath(item: item, section: 0))
        }
    }
    
}

Documentation是寫給公司老外看的脖卖,相信在座的都是中國人乒省,這種簡單的幾何不需要解釋了。如果對Layout有疑問的畦木,可以參考前一篇文章:http://www.reibang.com/p/47fca57fd30b

下面我們來看一下如何使用這個東西袖扛,首先你需要在你的StoryBoard里面把CollectionView對應(yīng)的Layout改掉:

Screen Shot 2017-04-17 at 7.25.16 PM.png

然后給這個Layout在對應(yīng)的ViewController里面創(chuàng)建一個屬性,lay back and enjoy:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var circularCollectionView: UICollectionView!
    @IBOutlet weak var circularLayout: CircularLayout!
    
    fileprivate var data = ["Zero","First","Second","Third","Forth","Fifth","Sixth","Seventh","Eighth","Ninth","Tenth","One", "Two", "Three"]
    fileprivate var realData:[String] = []
    fileprivate var count = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        circularCollectionView.register(UINib(nibName: "CircularCellCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CircularCell")
        circularCollectionView.delegate = CollectionFactory.shared
        circularCollectionView.dataSource = CollectionFactory.shared
        CollectionFactory.shared.delegate = self
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let vm = CollectionFactory.shared.registerViewModel(vm:CircularModel()) as! CircularModel
        circularLayout.delegate = vm
        Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { (timer) in
            if self.count < self.data.count {
                self.realData.append(self.data[self.count])
                self.count += 1
                DispatchQueue.main.async {
                    self.circularCollectionView.reloadData()
                }
            }else {
                self.count = 0
                timer.invalidate()
            }
            
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

extension ViewController:FactoryDataSource {
  
    var dataContainer:[Any]{return realData}
}

完整的project可以在這里找到:https://github.com/LHLL/CircularCollectionView

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末十籍,一起剝皮案震驚了整個濱河市蛆封,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌勾栗,老刑警劉巖惨篱,帶你破解...
    沈念sama閱讀 218,204評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異围俘,居然都是意外死亡砸讳,警方通過查閱死者的電腦和手機机断,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,091評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來绣夺,“玉大人吏奸,你說我怎么就攤上這事√账#” “怎么了奋蔚?”我有些...
    開封第一講書人閱讀 164,548評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長烈钞。 經(jīng)常有香客問我泊碑,道長,這世上最難降的妖魔是什么毯欣? 我笑而不...
    開封第一講書人閱讀 58,657評論 1 293
  • 正文 為了忘掉前任馒过,我火速辦了婚禮,結(jié)果婚禮上酗钞,老公的妹妹穿的比我還像新娘腹忽。我一直安慰自己,他們只是感情好砚作,可當我...
    茶點故事閱讀 67,689評論 6 392
  • 文/花漫 我一把揭開白布窘奏。 她就那樣靜靜地躺著,像睡著了一般葫录。 火紅的嫁衣襯著肌膚如雪着裹。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,554評論 1 305
  • 那天米同,我揣著相機與錄音骇扇,去河邊找鬼。 笑死面粮,一個胖子當著我的面吹牛少孝,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播但金,決...
    沈念sama閱讀 40,302評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼韭山,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了冷溃?” 一聲冷哼從身側(cè)響起钱磅,我...
    開封第一講書人閱讀 39,216評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎似枕,沒想到半個月后盖淡,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,661評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡凿歼,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,851評論 3 336
  • 正文 我和宋清朗相戀三年褪迟,在試婚紗的時候發(fā)現(xiàn)自己被綠了冗恨。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,977評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡味赃,死狀恐怖掀抹,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情心俗,我是刑警寧澤傲武,帶...
    沈念sama閱讀 35,697評論 5 347
  • 正文 年R本政府宣布,位于F島的核電站城榛,受9級特大地震影響揪利,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜狠持,卻給世界環(huán)境...
    茶點故事閱讀 41,306評論 3 330
  • 文/蒙蒙 一荡含、第九天 我趴在偏房一處隱蔽的房頂上張望婆跑。 院中可真熱鬧喉童,春花似錦侄泽、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,898評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至昭齐,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間矾柜,已是汗流浹背阱驾。 一陣腳步聲響...
    開封第一講書人閱讀 33,019評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留怪蔑,地道東北人里覆。 一個月前我還...
    沈念sama閱讀 48,138評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像缆瓣,于是被迫代替她去往敵國和親喧枷。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,927評論 2 355

推薦閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫弓坞、插件隧甚、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,103評論 4 62
  • Github地址:-CollectionViewLayout-CollectionViewFlowLayout- ...
    大沖哥閱讀 5,210評論 1 10
  • 楚楚佳麗胭脂粉,仙女化蝶戀紅塵渡冻。 花雨花潮花如雪戚扳,遠醉晴空近醉人。 春花尚可人族吻,只恨時日短……
    羽扇閑人閱讀 268評論 3 3
  • 親愛的自己 我想給你寫封信 信的內(nèi)容很簡單- 希望你一直不要放棄 十九載的時光 無法每分每秒都有意義 可我仍希望你...
    笨拳超人閱讀 281評論 0 0
  • 今天早上來給一小學妹代早自習帽借,打了一下她預留的電話珠增,確定一下教室,然后我打的時候砍艾,走在我前面的一群女生中有...
    馬賽曲閱讀 214評論 0 0