How to create collectionview cell one by one or one after another


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
})

ActivityIndicator programatically in swift


func showActivityIndicator(on parentView: UIView) {
let activityIndicator = UIActivityIndicatorView(style: .gray)
activityIndicator.startAnimating()
activityIndicator.translatesAutoresizingMaskIntoConstraints = false

parentView.addSubview(activityIndicator)

NSLayoutConstraint.activate([
activityIndicator.centerXAnchor.constraint(equalTo: parentView.centerXAnchor),
activityIndicator.centerYAnchor.constraint(equalTo: parentView.centerYAnchor),
])
}

how to use activityIndicator

start

showActivityIndicator(on: yourview)

stop

activityIndicator.stopAnimating()

How can i pop specific viewcontroller in swift.


for controller in self.navigationController!.viewControllers as Array {
if controller.isKind(of: ViewController.self) {
self.navigationController!.popToViewController(controller, animated: true)
break
}
}

OR Using Extension


extension UINavigationController {
func popToViewController(ofClass: AnyClass, animated: Bool = true) {
if let vc = viewControllers.filter({$0.isKind(of: ofClass)}).last {
popToViewController(vc, animated: animated)
}
}
}

how to use


navigationController?.popToViewController(ofClass: ViewController.self)

UITableView delegate and datasource using extensions swift

// MARK: - TableView DataSource
extension ViewController : UITableViewDataSource {

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath as IndexPath)
cell.textLabel!.text = "\(indexPath.row) Done"
return cell
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 3
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
}

// MARK: - TableView Delegate
extension ViewController: UITableViewDelegate {

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indexPath = tableView.indexPathForSelectedRow
let currentCell = tableView.cellForRow(at: indexPath!)!
print(currentCell.textLabel!.text!)

}
}

How to get dynamic height of string in swift


extension String {

    func height(constraintedWidth width: CGFloat, font: UIFont) -> CGFloat {

        let label =  UILabel(frame: CGRect(x: 0, y: 0, width: width, height: .greatestFiniteMagnitude))

        label.numberOfLines = 0

        label.font = font

        label.text = self

        label.sizeToFit()

        return label.frame.height

    }

}

how to use :

let height = yourString.height(constraintedWidth: yourStringWidth, font: UIFont(name: “Helvetica”, size: 16))
 

Get different between two date in swift.


extension Date {

      func From(date : Date) -> String {

        let dayHourMinuteSecond: Set = [.day, .hour, .minute]

        let difference = NSCalendar.current.dateComponents(dayHourMinuteSecond, from: date, to: self);

        let minutes = "\(difference.minute ?? 0) min ago"

        let hours = "\(difference.hour ?? 0) hour ago"

        let days = "\(difference.day ?? 0) day ago"

        if let day = difference.day, day          > 0 { return days }

        if let hour = difference.hour, hour       > 0 { return hours }

        if let minute = difference.minute, minute > 0 { return minutes }

        return ""

    } 

}

How to use :

Date().From(date: yourdate)

How use main thread using extension in swift

Description : if current thread is not main thread then block of code run in main thread.


extension Thread{
class func OnMainThread(_ completion: @escaping (()-> Void)){
      if Thread.current.isMainThread{
          completion()
          return
      }else{
          DispatchQueue.main.async {
              completion()
          }
      }
  }
}

How to use :-

Thread.OnMainThread{
    //Your Code Here
}

How to Add and Remove BlurEffectView using extension in swift


extension UIView {

    func blurView(style: UIBlurEffect.Style) {

        var blurEffectView = UIVisualEffectView()

        let blurEffect = UIBlurEffect(style: style)

        blurEffectView = UIVisualEffectView(effect: blurEffect)

        blurEffectView.frame = bounds

        insertSubview(blurEffectView, at: 0)

    }

How to Add :-

self.view.blurView(style: .light)


func removeBlurView() {

        for view in self.subviews {

            if let view = view as? UIVisualEffectView {

                view.removeFromSuperview()

            }

        }

    }

}

How to Remove :-

self.view.removeBlurView()