Swift Alert Toast With Code Examples

  • Updated
  • Posted in Programming
  • 5 mins read


Swift Alert Toast With Code Examples

In this session, we are going to strive our hand at fixing the Swift Alert Toast puzzle through the use of the pc language. The following piece of code will reveal this level.

/////////////////////////////////////////////////// Tested
//											///////
//				implementation				///////
//				Part 2						///////
//											///////
///////////////////////////////////////////////////
//right here we name Toast Bubble it inside our button "simply copy it in your controller"
 @IBOutlet weak var txtPassword: UITextField!
    @IBOutlet weak var txtUserName: UITextField!
    
    //MARK: Login Action
    
    @IBAction func btnLoginPressed(_ sender: UIButton) {
        if txtUserName.textual content == ""
        {
            //Call UIView extension technique
            self.view.presentToast(toastMessage: "Please Enter Username,beacuse it's vital so as to add For getting logged in.", period: 1.1)
        }
        else if txtPassword.textual content == ""
        {
            self.view.presentToast(toastMessage: "Please Enter Password.", period: 1.1)
        }
        else
        {
            //Do login
        }
        
    }
///////////////////////////////////////////////////
//											///////
//				create Toast				///////
//				Part 1						///////
//											///////
///////////////////////////////////////////////////
//This is Extention of toast "it's going to keep exterior controller"
import UIKit

//MARK: Add Toast technique perform in UIView Extension so can use in complete mission.
extension UIView
{
    func presentToast(toastMessage:String,period:CGFloat)
    {
        //View to blur bg and stopping person interplay
        let bgView = UIView(body: self.body)
        bgView.backgroundColor = UIColor(purple: CGFloat(255.0/255.0), inexperienced: CGFloat(255.0/255.0), blue: CGFloat(255.0/255.0), alpha: CGFloat(0.6))
        bgView.tag = 555
        
        //Label For displaying toast textual content
        let lblMessage = UILabel()
        lblMessage.numberOfLines = 0
        lblMessage.lineBreakMode = .byWordWrapping
        lblMessage.textColor = .white
        lblMessage.backgroundColor = .black
        lblMessage.textAlignment = .heart
        lblMessage.font = UIFont.init(title: "Helvetica Neue", dimension: 17)
        lblMessage.textual content = toastMessage
        
        //calculating toast label body as per message content material
        let maxSizeTitle : CGSize = CGSize(width: self.bounds.dimension.width-16, peak: self.bounds.dimension.peak)
        var expectedSizeTitle : CGSize = lblMessage.sizeThatFits(maxSizeTitle)
        // UILabel can return a dimension bigger than the max dimension when the variety of traces is 1
        expectedSizeTitle = CGSize(width:maxSizeTitle.width.getminimum(value2:expectedSizeTitle.width), peak: maxSizeTitle.peak.getminimum(value2:expectedSizeTitle.peak))
        lblMessage.body = CGRect(x:((self.bounds.dimension.width)/2) - ((expectedSizeTitle.width+16)/2) , y: (self.bounds.dimension.peak/2) - ((expectedSizeTitle.peak+16)/2), width: expectedSizeTitle.width+16, peak: expectedSizeTitle.peak+16)
        lblMessage.layer.cornerRadius = 8
        lblMessage.layer.masksToBounds = true
        lblMessage.padding = UIEdgeInunits(prime: 4, left: 4, backside: 4, proper: 4)
        bgView.addSubview(lblMessage)
        self.addSubview(bgView)
        lblMessage.alpha = 0
        
        UIView.animateKeyframes(withDuration:TimeInterval(period) , delay: 0, choices: [] , animations: {
            lblMessage.alpha = 1
        }, completion: {
            sucess in
            UIView.animate(withDuration:TimeInterval(period), delay: 8, choices: [] , animations: {
                lblMessage.alpha = 0
                bgView.alpha = 0
            })
            bgView.removeFromSuperview()
        })
    }
}
extension CGFloat
{
    func getminimum(value2:CGFloat)->CGFloat
    {
        if self < value2
        {
            return self
        }
        else
        {
            return value2
        }
    }
}

//MARK: Extension on UILabel for including insets - for including padding in prime, backside, proper, left.

extension UILabel
{
    non-public struct AssociatedKeys {
        static var padding = UIEdgeInunits()
    }
    
    var padding: UIEdgeInunits? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.padding) as? UIEdgeInunits
        }
        set {
            if let newValue = newValue {
                objc_setAssociatedObject(self, &AssociatedKeys.padding, newValue as UIEdgeInunits?, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }
    }
    
    override open func draw(_ rect: CGRect) {
        if let insets = padding {
            self.drawText(in: rect.inset(by: insets))
        } else {
            self.drawText(in: rect)
        }
    }
    
    override open var intrinsicContentSize: CGSize {
        get {
            var contentSize = tremendous.intrinsicContentSize
            if let insets = padding {
                contentSize.peak += insets.prime + insets.backside
                contentSize.width += insets.left + insets.proper
            }
            return contentSize
        }
    }
}


We have been in a position to reveal how one can appropriate the Swift Alert Toast bug by quite a lot of examples taken from the actual world.

How do you toast in Swift?

You can add ‘toastLabel. font = UIFont(title: “IranSansMobile”, dimension: 19)’ with a view to change font of toast message. The label must be faraway from the view when the animation ends.21-Jul-2015

What are toaster alerts?

Push notifications to your guests with a toast, a light-weight and simply customizable alert message. Toasts are light-weight notifications designed to imitate the push notifications which were popularized by cell and desktop working techniques. They’re constructed with flexbox, in order that they’re straightforward to align and place.

Does iOS have toast message?

Toasts are a local characteristic of Android, however iOS does not have this by default. If you solely want toasts on Android, you need to use the ToastAndroid API offered by React Native.

How do you present toast in swift 5?

Swift Package Manager When utilizing Xcode 11 or later, you possibly can set up Toast by going to your Project settings > Swift Packages and add the repository by offering the GitHub URL. Alternatively, you possibly can go to File > Swift Packages > Add Package Dependencies

What is a toast message?

A toast supplies easy suggestions about an operation in a small popup. It solely fills the quantity of house required for the message and the present exercise stays seen and interactive. Toasts mechanically disappear after a timeout.02-Sept-2022

What is just like toast in iOS?

Inspired by Android’s Toast,Loaf is a Swifty Framework for Easy iOS Toasts.

Why is it referred to as a toast message?

Mobile OS builders resembling Android and iOS needed to supply notifications to the customers. The factor popped up from the underside of the display screen, a movement which was very comparable of a toast popping up from the toaster when prepared — so toast it was referred to as.05-Nov-2020

Is toast a notification?

Google adopted the ideas of notification drawer and toast popup messages for person notifications as primary elements of its Android working system.

How do you set off toast?

Toasts could be triggered through JavaScript — simply name the toast() Bootstrap technique with the id , class or any CSS selector of the goal aspect in your JavaScript code.

What is the distinction between toast and snackbar?

Snackbars comprise a single line of textual content immediately associated to the operation carried out. They could comprise a textual content motion, however no icons. Toasts (Android solely) are primarily used for system messaging. They additionally show on the backside of the display screen, however might not be swiped off-screen.

Leave a Reply