2017-05-31 71 views
1

我有一年概述日历视图:提高的CollectionView加载速度

I build it to look exactly like the iOS Calendar

对于我有以下的观层次:

  • 的ViewController
    • 查看
      • 收藏查看有12个细胞(每月一)
        • Colleciton查看49个细胞(每天一个+进出日期星期+天)

现在,当它涉及到我加载的日子细胞概述内部下面的代码部分:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CalendarPageYearCollectionCellMonthCell; 

    print("cell for item at: \(indexPath.item)"); 

    cell.layer.shouldRasterize = true; 
    cell.layer.rasterizationScale = UIScreen.main.scale; 

    cell.label.text = self.days[indexPath.item]; 

    return cell; 
} 

此代码部分需要9秒。同时UI被冻结。如何显着提高这些单元格的加载和渲染速度,以便加载视图不会超过1秒钟?

编辑我发现哪部分代码需要消耗这段时间。我创建了一个UICollectionViewCell编程:

import Foundation 
import UIKit 
import SnapKit 

class CalendarPageYearCollectionCellMonthCell : UICollectionViewCell { 

    var label: UILabel! = nil; 

    override init(frame: CGRect) { 
     super.init(frame: frame); 

     self.setupView(); 
    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 

    func setupView() { 
     self.backgroundColor = UIColor.green; 

     self.label = UILabel(); 
     self.label.font = UIFont(name: "HelveticaNeue", size: 12); 
     self.label.textColor = PaintBox.colorWithName(VKBColor.black, andAlpha: 1.0); 
     self.label.backgroundColor = UIColor.red; 
     self.label.textAlignment = .center; 
     self.sizeToFit(); 
     self.label.center = self.center; 

     self.addSubview(self.label); 
    } 
} 

所以,当我使用此代码日历负荷真快。但有了这些代码,当然,你永远不会看到你添加为子视图的标签。所以我需要添加一些限制条件:

func setupView() { 
    self.backgroundColor = UIColor.green; 

    self.label = UILabel(); 
    self.label.font = UIFont(name: "HelveticaNeue", size: 12); 
    self.label.textColor = PaintBox.colorWithName(VKBColor.black, andAlpha: 1.0); 
    self.label.backgroundColor = UIColor.red; 
    self.label.textAlignment = .center; 
    self.sizeToFit(); 
    self.label.center = self.center; 

    self.addSubview(self.label); 

    self.label.snp.makeConstraints { make in 
     make.edges.equalToSuperview(); 
    } 
} 

现在需要花费时间才能加载视图。所以真正的问题似乎是约束。

还没有一种方法只创建一个单元格,并将其复制到所有其他单元格,只需设置文本?

+0

第一个问题:为什么光栅化?它看起来像非常简单的单元格 - 一个标签加上一个圆圈(仅在1天)... – DonMag

+0

这是我沮丧的尝试加快一切,因为它是我从研究中得到的唯一结果 – Mulgard

+0

您是否使用过仪器来确定在哪里花费时间? – jrturton

回答

0

因此经过大量研究后,我得出结论,我无法在使用故事板和约束条件时加快速度。地狱一直都很慢。

所以我试图摆脱所有的xib文件,故事板文件和约束。结果令人难以置信。我从9秒的视图加载速度到230毫秒的加载速度。

所以我推荐给大家:如果你有性能问题,只是不使用xib的,故事板或约束。只需编写一切代码并直接设置视图的所有框架即可。