Search code examples
swiftswiftmessages

SwiftMessage: how to handle action when user tap on outside of message view?


I'm using SwiftMessage in my project. when the specific message is showing on the screen, I want when the user tap on outside of the message view (anywhere else on message view), some actions happening. how can I do this?

update

I forgot to say I'm using SwiftMessage with one button.


Solution

  • Unfortunately, there isn't a way to add an action on tap outside of the MessageView.

    However, if your dimMode is interactive (has tap outside to dismiss enabled) you can easily catch .willHide and .didHide events using eventListeners of SwiftMessages.Config:

    let view = MessageView.viewFromNib(layout: .cardView)
    
    var config = SwiftMessages.defaultConfig
    config.dimMode = .gray(interactive: false)
    config.eventListeners.append { event in
        switch event {
        case .willHide:
            // Handle will hide
        case .didHide:
            // Handle did hide
        default:
            break
        }
    }
    SwiftMessages.show(config: config, view: view)
    

    Those events will be triggered on tap outside of the MessageView.

    Update: In your particular case where you have a button which have a different action from the tap outside action, you can use something like this:

    func showMessageView(buttonHandler: @escaping () -> Void, dismiss: @escaping () -> Void) {
        var buttonTapped = false
        let view = MessageView.viewFromNib(layout: .cardView)
        view.buttonTapHandler = { sender in
            buttonHandler()
            buttonTapped = true
        }
    
        var config = SwiftMessages.defaultConfig
        config.dimMode = .gray(interactive: false)
        config.eventListeners.append { event in
            if !buttonTapped, event == .didHide {
                dismiss()
            }
        }
        SwiftMessages.show(config: config, view: view)
    }
    

    That way when the button is tapped the dismiss closure will never run.