Home > Enterprise >  Extension files on Swift
Extension files on Swift

Time:10-22

Hey guys I'm learing swift and I just learned about extensions

so I have this in my UIViewController , how can i use this extension in a extension file so i reused in any other ViewController i want.

extension UIViewController {
  func showToast(message: String){
    let toast = UILabel(frame: CGRect(
        x: self.view.frame.width/2-75,
        y: self.view.frame.height - 100,
        width: 150, height: 40))
    toast.textAlignment = .center
    toast.backgroundColor = .label
    toast.textColor = .systemBackground
    toast.alpha = 1.0
    toast.layer.cornerRadius = 10
    toast.clipsToBounds = true
    toast.text = message
    self.view.addSubview(toast)
    
    UIView.animate(
        withDuration: 4.0,
        delay: 1.0,
        options: .curveEaseInOut,
        animations: {
            toast.alpha = 0.0
        }) { (isCompleted) in
            toast.removeFromSuperview()
        }
  }
}

CodePudding user response:

An extension simply defines methods that are available for every instance of the object that they extend.

So in the case of your extension, if you add that file to your project, every instance of UIViewController in your app will have access to your showToast(message:) method.

  • Related