TTGSnackbar shows simple message and action button on the bottom or top of the screen with multi kinds of animation, which is written in Swift3 and inspired by Snackbar in Android. It also support showing custom view, icon image or multi action button.

Overview

TTGSnackbar

A Swift based implementation of the Android Snackbar for iOS

Build Status Version License Platform Swift5 Apps Using Total Download

Screenshot

Gif

Screenshot

About

TTGSnackbar is useful for showing a brief message at bottom or top of the screen with one or two action buttons. It appears above all other elements on screen.
It disappears after a timeout or after user click the action button.

Installation

Swift 5

Version 1.9.0+ Xcode 9+ iOS 8+

Swift 4

Version 1.6.0 Xcode 9
iOS 8+

Swift 3

Version 1.5.3 Xcode 8
iOS 8+

CocoaPods

You can use CocoaPods to install TTGSnackbar by adding it to your Podfile:

pod "TTGSnackbar"

Carthage

You can use Carthage to install TTGSnackbar by adding it to your Cartfile:

github "zekunyan/TTGSnackbar"

Import

And you need to import the module.

import TTGSnackbar

Usage

Show a simple message

Example

let snackbar = TTGSnackbar(message: "TTGSnackbar !", duration: .short)
snackbar.show()

Show a simple message with an action button

Example

let snackbar = TTGSnackbar(
    message: "TTGSnackBar !",
    duration: .middle,
    actionText: "Action!",
    actionBlock: { (snackbar) in
        print("Click action!")
    }
)
snackbar.show()

Show a simple message with a long running action

Example

let snackbar = TTGSnackbar(
    message: "TTGSnackbar !",
    duration: .forever,
    actionText: "Action",
    actionBlock: { (snackbar) in
        print("Click action!")
        // Dismiss manually after 3 seconds
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(3 * Double(NSEC_PER_SEC))) / Doubl(NSEC_PER_SEC)) {
            snackbar.dismiss()
        }   
    }
)
snackbar.show()

Show a simple message with two action buttons

Example

let snackbar = TTGSnackbar(message: "Two actions !", duration: .long)

// Action 1
snackbar.actionText = "Yes"
snackbar.actionTextColor = UIColor.green
snackbar.actionBlock = { (snackbar) in NSLog("Click Yes !") }

// Action 2
snackbar.secondActionText = "No"
snackbar.secondActionTextColor = UIColor.yellow
snackbar.secondActionBlock = { (snackbar) in NSLog("Click No !") }

snackbar.show()

Show a simple message with an icon image

Example

let snackbar = TTGSnackbar(message: "TTGSnackbar !", duration: .long)

// Add icon image
snackbar.icon = UIImage(named: "emoji_cool_small")

snackbar.show()

[Improved!] Show custom content view in snackbar

Example

// Instantiate the custom content view
let customContentView = UINib(nibName: "CustomView", bundle:Bundle.main).instantiate(withOwner: nil, options: nil).first as! UIView?

// Initialize the snackbar with the custom content view
let snackbar = TTGSnackbar(customContentView: customContentView, duration: .long)

snackbar.show()

Make use of the Gesture recognizers in snackbar

Example

let snackbar = TTGSnackbar(message: "TTGSnackbar !", duration: .long)

// Add icon image
snackbar.icon = UIImage(named: "emoji_cool_small")

// Add the gesture recognizer callbacks
ssnackbar.onTapBlock = { snackbar in
    snackbar.dismiss()
}

snackbar.onSwipeBlock = { (snackbar, direction) in
    
    // Change the animation type to simulate being dismissed in that direction
    if direction == .right {
        snackbar.animationType = .slideFromLeftToRight
    } else if direction == .left {
        snackbar.animationType = .slideFromRightToLeft
    } else if direction == .up {
        snackbar.animationType = .slideFromTopBackToTop
    } else if direction == .down {
        snackbar.animationType = .slideFromTopBackToTop
    }
    
    snackbar.dismiss()
}

snackbar.show()

[New!] Automatic handling of Showing one Snackbar at a time

TTGSnackbarManager can handle automatically showing and replacing the presented Snackbars at your screen.

Note: This is an experimental feature that works only for message only snackbars at the moment.

let snackbar = TTGSnackbar(message: "TTGSnackbar !", duration: .long)
TTGSnackbarManager.show(snackbar)

TTGSnackbarManager uses the dismissBlock property of a snackbar, if you still need to use it you can use the dismissBlock parameter of TTGSnackbarManager.show(_: TTGSnackbar, dismissBlock: @escaping TTGDismissBlock) Example:

let snackbar = TTGSnackbar(message: "TTGSnackbar !", duration: .long)
TTGSnackbarManager.show(snackbar) {
    // Some dismiss block here
}

Customization

Message

message: String defines the message to display. Supports multi line text. Supports updating on the fly.

Message text color

messageTextColor: UIColor defines the message text color.

Message text font

messageTextFont: UIFont defines the message text font.

Display duration

duration: TTGSnackbarDurationdefines the display duration.
TTGSnackbarDuration : short, middle, long and forever. When you set forever, the snackbar will show an activity indicator after user click the action button and you must dismiss the snackbar manually.

Action title

actionText: String defines the action button title.

Action title color

actionTextColor: UIColor defines the action button title color.

Action title font

actionTextFont: UIFont defines the action button title font.

Action max width

actionMaxWidth: CGFloat defines the action button max width. Min is 44.

Action text number of lines

actionTextNumberOfLines: Int defines the number of lines of action button title. Default is 1.

Action callback

actionBlock: TTGActionBlock? will be called when user clicks the action button.

// TTGActionBlock definition.
public typealias TTGActionBlock = (snackbar: TTGSnackbar) -> Void

Second action title, color, font and callback

secondActionText: String  
secondActionTextColor: UIColor  
secondActionTextFont: UIFont  
secondActionBlock: TTGActionBlock?

Dismiss callback

dismissBlock: TTGDismissBlock? will be called when snackbar dismiss automatically or when user click action button to dismiss the snackbar.

// TTGDismissBlock definition.
public typealias TTGDismissBlock = (snackbar: TTGSnackbar) -> Void

On Tap Gesture callback

onTapBlock: TTGActionBlock will be called when the user taps the snackbar.

// TTGActionBlock definition.
public typealias TTGActionBlock = (snackbar: TTGSnackbar) -> Void

On Swipe Gesture callback

onSwipeBlock: TTGSwipeBlock will be called when the user swipes on the snackbar

/// Swipe gesture callback closure
public typealias TTGSwipeBlock = (_ snackbar: TTGSnackbar, _ direction: UISwipeGestureRecognizerDirection) -> Void

Auto Dismissal using Swipe Gestures

shouldDismissOnSwipe: Bool will determine if the snackbar will automatically be dismissed when it's swiped

/// A property to make the snackbar auto dismiss on Swipe Gesture
public var shouldDismissOnSwipe: Bool = false

Animation type

animationType: TTGSnackbarAnimationType defines the style of snackbar when it show and dismiss.

TTGSnackbarAnimationType : fadeInFadeOut, slideFromBottomToTop, slideFromBottomBackToBottom, slideFromLeftToRight, slideFromRightToLeft, slideFromTopToBottom and slideFromTopBackToTop.

The default value of animationType is slideFromBottomBackToBottom, which is the same as Snackbar in Android.

Animation duration

animationDuration: NSTimeInterval defines the duration of show and hide animation.

Margins

leftMargin: CGFloat, rightMargin: CGFloat, topMargin: CGFloat and bottomMargin: CGFloat defines the margins of snackbar

[New!] Custom Content View to follow left and right margins

shouldActivateLeftAndRightMarginOnCustomContentView: Bool will activate the left and right margins if using a customContentView

/// a property to enable left and right margin when using customContentView
public var shouldActivateLeftAndRightMarginOnCustomContentView: Bool = false

Padding (Content inset)

contentInset: UIEdgeInsets defines the padding(content inset) of content in the snackbar. Default is UIEdgeInsets.init(top: 0, left: 4, bottom: 0, right: 4).

Corner radius

cornerRadius: CGFloat defines the corner radius of snackbar.

Icon image

icon: UIImage defines the icon image.

Icon image content mode

iconContentMode: UIViewContentMode defines the content mode of icon imageView.

[New!] Custom container view

containerView: UIView defines the custom container(super) view for snackbar to show.

[New!] Custom content view

customContentView: UIView? defines the custom content view to show in the snackbar.

[New!] Separator line view background color

separateViewBackgroundColor: UIColor = UIColor.gray defines the separator line color.

ActivityIndicatorViewStyle

activityIndicatorViewStyle: UIActivityIndicatorViewStyle defines the activityIndicatorViewStyle in snackbar.

ActivityIndicatorView color

activityIndicatorViewColor: UIColor defines the activityIndicatorView color in snackbar.

Animation SpringWithDamping

animationSpringWithDamping: CGFloat defines the spring animation damping value. Default is 0.7.

Animation initialSpringVelocity

animationInitialSpringVelocity: CGFloat defines the spring animation initial velocity. Default is 5.

Contact me

[email protected]

Comments
  • Updated to 1.10.0 now crashes (sometimes) on startup...

    Updated to 1.10.0 now crashes (sometimes) on startup...

    I (mindlessly) updated pods yesterday, did a build, and released my application to TestFlight. I made a minor change, so just wanted to see what testing did.

    My TTGSnackbar updated (I believe) from:

    TTGSnackbar 1.9.2 -> 1.10.0
    

    ... and it has started crashing on a TTGSnackbar I raise (from main thread) on close to app startup (after a network call.) It is intermittent .. so timing related. I don't have much detail (sadly) 'cos Xcode hates me, and has never given me a decent stack trace. All I get I will try to share as attachments.

    Both reporters are on iOS 13.3.1.

    I am going to revert to 1.9.2 to see if the problem goes away. I'll report results here. Stack1 Stack2

    opened by adamjack 10
  • Force unwrapping of (superview?.frame)! can cause a crash in rare circumstances

    Force unwrapping of (superview?.frame)! can cause a crash in rare circumstances

    Got this crash in production code:

    Crashed: com.apple.main-thread 0 TTGSnackbar 0x10107dd94 TTGSnackbar.dismissAnimated(Bool) -> () (TTGSnackbar.swift:619) 1 TTGSnackbar 0x1010808f4 partial apply for TTGSnackbar.(dismiss() -> ()).(closure #1) (TTGSnackbar.swift) 2 libdispatch.dylib 0x1914de9e0 _dispatch_call_block_and_release + 24 3 libdispatch.dylib 0x1914de9a0 _dispatch_client_callout + 16

    It's extremely rare, like, 1/50,000.

    perhaps switch to:

    if let superViewWidth = (superview?.frame)!.width {
       do thing
    } else {
      handle error
    }
    

    ?

    opened by RamblinWreck77 10
  • Added method to change the leftPadding (space between snackbar and ...

    Added method to change the leftPadding (space between snackbar and ...

    icon/label).

    img_0012

    When setting the left margin to 0 I found that the left padding was too low. So i decided to do this enhancement.

    It works by adding a new constraint that can be altered. The 2 pixel distance of iconImageView will be removed because of the 500 priority, when the left padding is set to a different value.

    The default left padding is still 2, so nothing changes for anybody except someone alters the left padding.

    opened by rcpfuchs 5
  • Allow to only have an icon on action button

    Allow to only have an icon on action button

    Hi, first thank for this component, I've added a small improvement I need to have : usage of an icon for the action button

    Added button to the example app to show this Added var to Snackbar class to allow actionIcon customization

    opened by kenji21 4
  • Animation Time

    Animation Time

    When the animation time is increased the snackbar does not dismiss when dismiss is called from an action on iOS 10. When the animation duration is set to like 1. then it is still okay, but anything more than that makes it unresponsive.

    opened by percyPolymorph 4
  • issue with ios 13

    issue with ios 13

    it seems that snackbar doesn't appear on ios 13, i've removed this line on show function: currentWindow = UIApplication.shared.windows.filter({$0.windowScene?.activationState == .foregroundActive}).first! (ine 584) also replacing with UIApplication.shared.windows.first { $0.isKeyWindow } works fine

    opened by seraph3b 3
  • Custom duration

    Custom duration

    Hello,

    It seems currently that the snackbar duration is tied to an integer enum.

    Would it be possible to create a new initializer that takes in an int as the duration property rather than tying it strictly to an enum? That way we are not restricted to 1, 3, 5 or forever.

    Thanks!

    opened by kelvinleague 3
  • TTGSnackbar Hidden Under The Keyboard

    TTGSnackbar Hidden Under The Keyboard

    When showing the TTGSnackbar on a view with an active keyboard on screen, the TTGSnackbar is shown under the keyboard and thus not visible to the user.

    opened by musbaalbaki 3
  • Handling iPhone X bottom offset

    Handling iPhone X bottom offset

    Snackbars render outside of the "safe area" that allow UI elements to not conflict or become obscured by iPhone X UI elements. This can result in the iPhone X's bottom home bar rendering on top of the Snackbar's content.

    There are a few workarounds to deal with this in our own apps. We can increase or assign the bottomOffset property of the snackbar manually, depending on whether the device is an iPhone X. However, this is not ideal because Apple does not offer a clean way of detecting the iPhone X screen type, the offset will have to be hardcoded, and the code is not forward compatible with other screen types.

    An alternative would be for TTGSnackbar to use safeArea in the bottom constraint (or offer it as a configuration option). Here is a basic example of how this could be accomplished:

    https://github.com/shaysemireg/TTGSnackbar/commit/7216df3d80cada2be6d4d6569f206238d479c3fd

    opened by shaysemireg 3
  • XCode 9, Objective-C, 1.6.0. Compile-time errors

    XCode 9, Objective-C, 1.6.0. Compile-time errors

    I knew nothing about Swift, so if you could point me out, why No visible @interface for 'TTGSnackbar' declares the selector 'show' error appears. Guess it's Extension namespace visibility problems. Any idea how to fix it? Everything works just fine before i moved out to XCode 9.0 and updated Pod. [[TTGSnackbar alloc] initWithMessage:message duration:TTGSnackbarDurationShort]; Also show the same type of error

    opened by zykis 3
  • Center the text without using a CustomView

    Center the text without using a CustomView

    Is there a way of centering the text field without using a CustomView? While this looks simple enough, I haven't found it nowhere in the documentation. Thanks!

    opened by bernaferrari 3
  • Swift Compiler Warnings

    Swift Compiler Warnings

    When the app target is iOS 13 or above, the swift compiler is showing warnings about deprecated code.

    Example: /Pods/TTGSnackbar/TTGSnackbar/TTGSnackbar.swift:926:69: 'white' was deprecated in iOS 13.0: renamed to 'UIActivityIndicatorView.Style.medium'

    opened by sarahbee 0
  • text direction

    text direction

    Dear Sir, Thanks so much for your very nice IOS Snackbar. I am newbie to XCODE, and found it very helpful. I just want to know if the control support right to left text direction ?

    Thanks,

    opened by waleedmakarem 0
  • Ability to choose View to display

    Ability to choose View to display

    Seems that the snackbar is display on UIWindow. If we pop a ViewController, we have to manage the dismiss manually on viewDidAppear for exemple. Will be nice if we could handle ourself the "parent ViewController"

    opened by SaezChristopher 0
Owner
zekunyan
iOS Programmer
zekunyan
Multiplatform (iOS, macOS) SwiftUI bottom sheet drawer. Expandable bottomsheet. Slide out bottom menu

Multiplatform (iOS, macOS) SwiftUI bottom sheet drawer Features It does not re-render the background content while manipulating with the sheet iOS and

Igor 8 Nov 18, 2022
Native alert from Apple Music & Feedback. Contains Done, Heart & Message and other presets. Support SwiftUI.

SPAlert Popup from Apple Music & Feedback in AppStore. Contains Done, Heart, Error and other presets. Supports Dark Mode. I tried to recreate Apple's

Ivan Vorobei 1.4k Dec 10, 2021
BottomSheet makes it easy to add custom bottom sheets to your SwiftUI apps.

BottomSheet About BottomSheet BottomSheet makes it easy to add custom bottom sheets to your SwiftUI apps. The result can look like this...or completel

Daniel Saidi 174 Jan 2, 2023
A message bar for iOS written in Swift.

Dodo, a message bar for iOS / Swift This is a UI widget for showing text messages in iOS apps. It is useful for showing short messages to the user, so

Evgenii Neumerzhitckii 874 Dec 13, 2022
A message bar for iOS written in Swift.

Dodo, a message bar for iOS / Swift This is a UI widget for showing text messages in iOS apps. It is useful for showing short messages to the user, so

Evgenii Neumerzhitckii 874 Dec 13, 2022
A Floating Action Button just like Google inbox for iOS

VCFloatingActionButton A Floating Action Button inspired from Google inbox for iOS. Using this in your project Import the VCFloatingActionButton to yo

Giridhar 298 May 16, 2022
Lightweight dropdown message bar in Swift. It's simple and beautiful.

SwiftyDrop SwiftyDrop is a lightweight pure Swift simple and beautiful dropdown message. Features Easy to use like: Drop.down("Message") Message field

Morita Naoki 691 Nov 20, 2022
BottomSheetDemo - Bottom sheet modal view controller with swift

当我们想弹出一个预览视图,bottom sheet modal view controller 非常实用。在 iOS 中,长按拖拽手势可以让 controlle

null 8 Oct 29, 2022
It is a highly configurable iOS library which allows easy styling with built in styles as well as extra header and footer views so that you can make extremely unique alerts and action sheets.

 CFAlertViewController CFAlertViewController is a library that helps you display and customise Alerts, Action Sheets, and Notifications on iPad and i

Crowdfire Inc. 1.1k Dec 18, 2022
Action sheet allows including your custom views and buttons.

CustomizableActionSheet Action sheet allows including your custom views and buttons. Installation CocoaPods Edit your Podfile: pod 'CustomizableAction

Ryuta Kibe 191 Nov 26, 2021
Native alert from Apple Music & Feedback. Contains Done, Heart & Message and other presets.

SPAlert Popup from Apple Music & Feedback in AppStore. Contains Done, Heart, Error and other presets. Supports Dark Mode. I tried to recreate Apple's

Ivan Vorobei 1.8k Jan 7, 2023
Bursts 🔥 A Funny Framework is showing alerts, Have been Adapting Swift and SwiftUI

Bursts ?? A Funny Framework is showing alerts, Have been Adapting Swift and SwiftUI Features iOS 10+ Can be used in UIKit and SwiftUI applications Lig

Jovins 11 Apr 22, 2022
A µFramework for showing alerts like the one used when copying from pasteboard or connecting Apple pencil

Drops ?? A µFramework for showing alerts like the one used when copying from pasteboard or connecting Apple pencil. Features iOS 10+ Can be used in Sw

Omar Albeik 709 Dec 29, 2022
A crisp in-app notification/message banner built in Swift.

RMessage Screenshots Intro Welcome to RMessage! RMessage is a simple notification library written in Swift to help you display notification on the scr

Adonis Peralta 407 Nov 29, 2022
Simple Alert View written in Swift, which can be used as a UIAlertController. (AlertController/AlertView/ActionSheet)

DOAlertController Simple Alert View written in Swift, which can be used as a UIAlertController replacement. It supports from iOS7! It is simple and ea

Daiki Okumura 406 Sep 5, 2022
A simple custom popup dialog view for iOS written in Swift. Replaces UIAlertController alert style.

A simple custom popup dialog view for iOS written in Swift. Replaces UIAlertController alert style.

donggyu 5 Jan 26, 2022
Fully customizable and extensible action sheet controller written in Swift

XLActionController By XMARTLABS. XLActionController is an extensible library to quickly create any custom action sheet controller. Examples The action

xmartlabs 3.3k Dec 31, 2022
SwiftUI Draggable Bottom Sheet

SwiftUI Draggable Bottom Sheet

paigeshin 2 Mar 3, 2022
Customizable Dynamic Bottom Sheet Library for iOS

DynamicBottomSheet Powerd by Witi Corp., Seoul, South Korea. Fully Customizable Dynamic Bottom Sheet Library for iOS. This library doesn't support sto

Witi Official 10 May 7, 2022