Skip to content

Instantly share code, notes, and snippets.

@dkulundzic
Created February 2, 2023 12:39
Show Gist options
  • Save dkulundzic/4a5aacc3f00c5504791b818ef15d5d07 to your computer and use it in GitHub Desktop.
Save dkulundzic/4a5aacc3f00c5504791b818ef15d5d07 to your computer and use it in GitHub Desktop.
Protocol based mechanism for easily and uniformly displaying a custom messaging UI element
protocol MessageViewPresentable: AnyObject {
var messageView: MessageView? { get set }
var hostView: UIView { get }
func showMessageView(using context: MessageView.Context, action: Action?)
func hideMessageView(animated: Bool)
}
extension MessageViewPresentable where Self: UIViewController {
var hostView: UIView {
view
}
func showMessageView(using context: MessageView.Context, action: Action?) {
let messageView = MessageView(context: context, action: action)
let oldMessageView = self.messageView
self.messageView = messageView
Animation.transition(with: view) {
oldMessageView?.removeFromSuperview()
self.hostView.addSubview(messageView)
messageView.snp.makeConstraints {
$0.edges.equalToSuperview()
}
}
}
func hideMessageView(animated: Bool) {
guard let messageView = messageView, messageView.isDescendant(of: view) else { return }
Animation.transition(with: view, animated: animated) {
messageView.removeFromSuperview()
self.messageView = nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment