class viewcontroller: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
var YourArr = [String]()
var timer = Timer()
var counter = 0
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(self.nameOfFunction), name: NSNotification.Name(rawValue: "nameOfNotification"), object: nil)
self.YourArr.append("")
self.timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(AddCellToCollectionView), userInfo: nil, repeats: true)
}
//MARK: - CollectionView Delegate
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return YourArr.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath as IndexPath)
cell.backgroundColor = .red
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let width = (collectionView.frame.size.width-20)/2
let height = width
let cellSize = CGSize(width: width, height: height)
return cellSize
}
//MARK: - Timer
@objc func AddCellToCollectionView(){
self.counter += 1
if counter < 30 {
self.YourArr.append("")
self.collectionView.reloadData()
}else{
self.timer.invalidate()
}
}
}
Note :-
if you want to add cell without reload collectionviewe then install pod
pod ‘DeepDiff’
and reload collection view instead use below code
var oldItems = YourArr
YourArr.append("")
let newItems = YourArr
let changes = diff(old: oldItems, new: newItems)
self.collectionView.reload(changes: changes, section: 0, updateData: {
oldItems = newItems
})