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

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

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

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

基本思路還是利用CollectionViewLayout來(lái)客制化CollectionView的外觀,既然如此,那么我們先創(chuàng)建一個(gè)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是寫給公司老外看的,相信在座的都是中國(guó)人,這種簡(jiǎn)單的幾何不需要解釋了。如果對(duì)Layout有疑問(wèn)的,可以參考前一篇文章:http://www.lxweimin.com/p/47fca57fd30b

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

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

然后給這個(gè)Layout在對(duì)應(yīng)的ViewController里面創(chuàng)建一個(gè)屬性,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)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,606評(píng)論 6 533
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,582評(píng)論 3 418
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人,你說(shuō)我怎么就攤上這事。” “怎么了?”我有些...
    開(kāi)封第一講書人閱讀 176,540評(píng)論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書人閱讀 63,028評(píng)論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,801評(píng)論 6 410
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書人閱讀 55,223評(píng)論 1 324
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,294評(píng)論 3 442
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書人閱讀 42,442評(píng)論 0 289
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,976評(píng)論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,800評(píng)論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,996評(píng)論 1 369
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,543評(píng)論 5 360
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,233評(píng)論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 34,662評(píng)論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 35,926評(píng)論 1 286
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,702評(píng)論 3 392
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,991評(píng)論 2 374

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

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