Giter Site home page Giter Site logo

sanzaru / simpletoast Goto Github PK

View Code? Open in Web Editor NEW
338.0 4.0 33.0 76 KB

SimpleToast is a simple, lightweight, flexible and easy to use library to show toasts / popup notifications inside iOS or MacOS applications in SwiftUI. Because of the flexibility to show any content it is also possible to use the library for showing simple modals.

License: Apache License 2.0

Swift 90.78% Ruby 9.22%
swiftui swift swift5 ios macos swift-package toast popup toast-notifications notification

simpletoast's Introduction

SimpleToast for SwiftUI

Build Status

SimpleToast is a simple, lightweight, flexible and easy to use library to show toasts / popup notifications inside iOS or macOS applications in SwiftUI. Because of the flexibility to show any content it is also possible to use the library for showing simple modals.

You decide the content, the library takes care about the rest.

⚠️ Note: The current version is still in development. There can and will be breaking changes in version updates until version 1.0.

Features:

  • Custom toast content support: You can show whatever you want inside the toast.
  • Custom positioning: Place the toast where you want it to be.
  • Timeout functionality: You decide if and when the toast should disappear.
  • Callback functionality: Run code when the toast disappeared.
  • Multiple, customizable animations

🚨 Breaking changes:

0.6.0:

  • The options struct is modified and the parameters showBackdrop and backdropColor are replaced by a single optional Color definition backdrop. See Options for more information

Demo

Modifier Demo
.slide
.fade
.scale
.skew

Installation

Swift Package Manager

dependencies: [
    .package(url: "https://github.com/sanzaru/SimpleToast.git", from: "0.0.1")
]

Cocoapods

Add the following line to your Podfile:

pod 'SwiftUI-SimpleToast', :git => 'https://github.com/sanzaru/SimpleToast.git'

and run

pod install

or

pod update

Usage:

There are different ways of attaching a toast notification to your view. The usage is very similar to well know SwiftUI view modifiers (e.g. alert or sheet). If you are familiar with these, using SimpleToast should be quiet easy.

Note: The toast always appears at the edges to the view it is attached to. Make sure the view has enough space to render the toast. Preferably the toast should be attached to the most outer view or the navigation view, if available.

Attach via boolean

You can attach the toast to a view and show it via binding to a boolean:

import SwiftUI
import SimpleToast

struct ToastTestView: View {
    @State var showToast: Bool = false

    private let toastOptions = SimpleToastOptions(
        hideAfter: 5
    )

    VStack(spacing: 20) {
        Button("Show toast") {
            withAnimation {
                showToast.toggle()
            }
        }
    }
    .simpleToast(isPresented: $showToast, options: toastOptions) {
        Label("This is some simple toast message.", systemImage: "exclamationmark.triangle")
        .padding()
        .background(Color.red.opacity(0.8))
        .foregroundColor(Color.white)
        .cornerRadius(10)
        .padding(.top)
    }
}

Attach via optional object

You can trigger the toast via an instance to an optional object, which conforms to the protocol Identifiable. If the value is not nil the toast will be shown.

The following example is based on the previous one and also shows the toast, but this time based on a value on an item.

import SwiftUI
import SimpleToast

struct ToastTestView: View {
    @State var showToast: DummyItem? = nil

    private struct DummyItem: Identifiable {
        var foo: String = "Bar"
    }

    private let toastOptions = SimpleToastOptions(
        hideAfter: 5
    )

    VStack(spacing: 20) {
        Button("Show toast") {
            withAnimation {
                // Toggle the item
                showToast = showToast == nil ? DummyItem() : nil
            }
        }
    }
    .simpleToast(item: $showToast, options: toastOptions) {
        HStack {
            Image(systemName: "exclamationmark.triangle")
            Text("This is some simple toast message.")
        }
        .padding()
        .background(Color.red.opacity(0.8))
        .foregroundColor(Color.white)
        .cornerRadius(10)
    }
}

 
ℹ️ This functionality is similar to the one of the SwiftUI sheet(item:onDismiss:content:)
 

Run code after dismissal

To run custom code after the toast disappeared you just have to pass a function to the onDismiss parameter:

import SwiftUI
import SimpleToast

struct ToastTestView: View {
    @State var showToast: Bool = false

    private let toastOptions = SimpleToastOptions(
        hideAfter: 5
    )

    VStack(spacing: 20) {
        Button("Show toast") {
            withAnimation {
                showToast.toggle()
            }
        }
    }
    .simpleToast(isShowing: $showToast, options: toastOptions, onDismiss: onToastComplete) {
        HStack {
            Image(systemName: "exclamationmark.triangle")
            Text("This is some simple toast message.")
        }
        .padding()
        .background(Color.red.opacity(0.8))
        .foregroundColor(Color.white)
        .cornerRadius(10)
    }

    // This will be called on toast completion
    func onToastComplete() -> Void {
        print("The toast did disappear")
    }
}

Usage with edgesIgnoringSafeArea(:edges:) / ignoresSafeArea(:edges:)

If the view you're attaching the toast to is ignoring a safe area, make sure to apply the SimpleToast modifier after the modifier for ignoring the safe area:

VStack {
    Text("Some view")
}
.ignoresSafeArea(.all)
.simpleToast(
    ...

Options

The toast can be configured via an optional SimpleToastOptions object. You can simply pass an empty object to configure the toast with default values.

 
📌 All parameters inside the options are optional. If not set, the default value will be taken.
 

Option Type Description Default
alignment Alignment Defines the alignment of the toast. .top
hideAfter TimeInterval? Defines when the toast disappears. If nil is given the toast won't disappear. nil
backdrop Color? Defines the backdrop color nil
animation Animation Defines the animation type. .linear
modifierType ModifierType Defines the type of toast animation. Possible values: .slide, .fade .fade
dismissOnTap Bool? Defines if the toast closes on tap. Possible values: true, false true

simpletoast's People

Contributors

adrianorezena avatar hossinasaadi avatar kyle-ye avatar nibe avatar sanzaru avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

simpletoast's Issues

Support custom views as backdrop

The option backdrop of SimpleToastOptions currently only supports the data type Color. It should be possible to use any type of view as a backdrop, so that a users can create and use their custom views as backdrop.

SimpleToast is blocking tvOS preview

For a multi platform projects, we can conditional link it to exclude tvOS in building and also use #canImport in Swift code.

image

This works fine for building and archiving. However this will cause an issue when previewing SwiftUI view on tvOS.

== PREVIEW UPDATE ERROR:

    SchemeBuildError: Failed to build the scheme ”Forumate”
    
    'DragGesture' is unavailable in tvOS
    
    Compile SimpleToast.swift (arm64):
    /Users/kyle/Library/Developer/Xcode/DerivedData/Forumate-cfcvrozqvmyfrfcrzfasktaukvys/SourcePackages/checkouts/SimpleToast/Sources/SimpleToast/SimpleToast.swift:30:9: error: 'DragGesture' is unavailable in tvOS
            DragGesture()
            ^~~~~~~~~~~

iOS 13: Empty content

Attaching the toast to a view in iOS 13 results in empty content.
Researching the issue showed that wrapping the content inside any kind of stack inside the view modifier sets the content empty.

Toast Message Issue

The message in the toast does not change if we set the global variable for the toast message.

Toast wont disappear

This library used to work for me but ever since I made some slight changes, once the toast appear, it never leaves. These are the options im using:

private let toastOptions = SimpleToastOptions(alignment: .bottom, hideAfter: 4, showBackdrop: false, backdropColor: Color.clear, animation: .easeInOut, modifierType: .slide)

Timer not updated on Toast appear

Setting a timeout of X seconds for the toast and triggering it multiple times inside a timeframe X-n, where n > 0, the timer won't be updated and the toast disappears to early.

Example: Setting the timer to a timeout to hide of 5 seconds and triggering the toast after 2 seconds the second time, the toast will disappear after 3 seconds, instead of 5.

Binding to item

It should be possible for the toast to be bound to an optional item, likewise to the sheet inside iOS, instead of just a binding to a boolean.

Dynamic content support

.simpleToast(item: $showToast, options: toastOptions) { HStack { Image(systemName: "exclamationmark.triangle") Text("This is some simple toast message.") } .padding() .background(Color.red.opacity(0.8)) .foregroundColor(Color.white) .cornerRadius(10) }

I need dynamic content support with item in. This doesn't work for me.

.simpleToast(item: $showToast, options: toastOptions) { item in HStack { Image(systemName: "exclamationmark.triangle") Text(item.message) } .padding() .background(Color.red.opacity(0.8)) .foregroundColor(Color.white) .cornerRadius(10) }

Toast not showing asynchronously fetched content

In case the content of the toast is fetched asynchronously, it is not being displayed inside the toast and instead just trigger an empty toast. Debugging the request shows that the content was fetched correctly, but is empty inside the toast view.

Example:

...

@State private var asyncMessage: String = ""

... 

Button("Trigger async action") {
    withAnimation {
        let url = URL(string: "https://jsonplaceholder.typicode.com")!
        URLSession.shared.dataTask(with: url) { data, response, error in
            DispatchQueue.main.async {
                asyncMessage = String(data: data!, encoding: .utf8)!
                print(asyncMessage)
                showToastAsync = !asyncMessage.isEmpty
            }
        }
        .resume()
    }
}

... 

.simpleToast(isShowing: $showToastAsync, options: optionsScale) {
    Text(asyncMessage)
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.