How do I present error banners in UIKit with Swift?

Swift, UIKit, error banners, error handling, iOS development
Learn how to present error banners in UIKit with Swift, enhancing user experience during error handling.
import UIKit class ErrorBanner { static func showError(in view: UIView, message: String) { let banner = UIView() banner.backgroundColor = UIColor.red banner.layer.cornerRadius = 10 banner.translatesAutoresizingMaskIntoConstraints = false let label = UILabel() label.text = message label.textColor = UIColor.white label.translatesAutoresizingMaskIntoConstraints = false banner.addSubview(label) view.addSubview(banner) NSLayoutConstraint.activate([ banner.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16), banner.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16), banner.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 16), label.centerYAnchor.constraint(equalTo: banner.centerYAnchor), label.leadingAnchor.constraint(equalTo: banner.leadingAnchor, constant: 16), label.trailingAnchor.constraint(equalTo: banner.trailingAnchor, constant: -16), banner.heightAnchor.constraint(equalToConstant: 50) ]) UIView.animate(withDuration: 0.5, animations: { banner.alpha = 1 }, completion: nil) // Remove banner after a delay DispatchQueue.main.asyncAfter(deadline: .now() + 3) { UIView.animate(withDuration: 0.5, animations: { banner.alpha = 0 }) { _ in banner.removeFromSuperview() } } } }

Swift UIKit error banners error handling iOS development