Home / IOS Development / iOS Swift Tutorial – How to implement iOS Toast Message with animation?

iOS Swift Tutorial – How to implement iOS Toast Message with animation?



Suppose you want to display some messages for a few seconds to notify users of a particular action, which method would you use? We have noticed that many iPhone app developers use UIAlertView to achieve this goal. While UIAlertView is a good option for displaying some messages / titles, but the problem is that the user has to close the alert message manually.

Normally it looks like this:

iOS pop-up alert message

Now, what if you want to show the same message for some time, and after that the message should be hidden automatically? The answer is iOS Toast notification used for this purpose.

What is Toast Message?

A toast message in iOS is a small, short-lived popup that provides a small piece of information to users.

It looks something like this:

bowl sample

In this iOS Swift tutorial we will learn how to implement an iOS toast message in your iPhone app, but we will also show you how to add animation to it.

Steps to implement iOS Toast Message with animation

In this demo we will show Toast Alert with Blur animation when the username or password field becomes blank and a user presses the Login button.

Step 1: First go to XCode and create a new project.

create a new project in xcode

Step 2: Now select the project type as a single view application and click next.

select single view application

Step 3: In the next tab, enter the project name and proceed.

select options for your new ios toast messaging project

Step – 4: After creating a new project, go to the Main.Storyboard, select ViewController and drop UITextField from the “Show Object Library” section.

go to main storyboard

Now you can also repeat this step for the password.

Step 5: Then go to Main.Storyboard, select ViewController and release UIButton from the “Show Object Library” section.

Step – 6: After adding the button, the final user interface should look like this:

latest user interface for toast message

Step – 7: Once you have the user interface ready that is similar to the image above, it is time to create an event for the login button.

create an event

Step 8: Now that you have created the event, it is time to implement the animation on toast.

make animation bowl

import UIKit

//MARK: Add Toast method function in UIView Extension so can use in whole project.
extension UIView
{
func showToast(toastMessage:String,duration:CGFloat)
{
//View to blur bg and stopping user interaction
let bgView = UIView(frame: self.frame)
bgView.backgroundColor = UIColor(red: CGFloat(255.0/255.0), green: CGFloat(255.0/255.0), blue: CGFloat(255.0/255.0), alpha: CGFloat(0.6))
bgView.tag = 555

//Label For showing toast text
let lblMessage = UILabel()
lblMessage.numberOfLines = 0
lblMessage.lineBreakMode = .byWordWrapping
lblMessage.textColor = .white
lblMessage.backgroundColor = .black
lblMessage.textAlignment = .center
lblMessage.font = UIFont.init(name: "Helvetica Neue", size: 17)
lblMessage.text = toastMessage

//calculating toast label frame as per message content
let maxSizeTitle : CGSize = CGSize(width: self.bounds.size.width-16, height: self.bounds.size.height)
var expectedSizeTitle : CGSize = lblMessage.sizeThatFits(maxSizeTitle)
// UILabel can return a size larger than the max size when the number of lines is 1
expectedSizeTitle = CGSize(width:maxSizeTitle.width.getminimum(value2:expectedSizeTitle.width), height: maxSizeTitle.height.getminimum(value2:expectedSizeTitle.height))
lblMessage.frame = CGRect(x:((self.bounds.size.width)/2) - ((expectedSizeTitle.width+16)/2) , y: (self.bounds.size.height/2) - ((expectedSizeTitle.height+16)/2), width: expectedSizeTitle.width+16, height: expectedSizeTitle.height+16)
lblMessage.layer.cornerRadius = 8
lblMessage.layer.masksToBounds = true
lblMessage.padding = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4)
bgView.addSubview(lblMessage)
self.addSubview(bgView)
lblMessage.alpha = 0

UIView.animateKeyframes(withDuration:TimeInterval(duration) , delay: 0, options: [] , animations: {
lblMessage.alpha = 1
}, completion: {
sucess in
UIView.animate(withDuration:TimeInterval(duration), delay: 8, options: [] , 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 adding insets - for adding padding in top, bottom, right, left.

extension UILabel
{
private struct AssociatedKeys {
static var padding = UIEdgeInsets()
}

var padding: UIEdgeInsets? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.padding) as? UIEdgeInsets
}
set {
if let newValue = newValue {
objc_setAssociatedObject(self, &AssociatedKeys.padding, newValue as UIEdgeInsets!, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}

override open func draw(_ rect: CGRect) {
if let insets = padding {
self.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
} else {
self.drawText(in: rect)
}
}

override open var intrinsicContentSize: CGSize {
get {
var contentSize = super.intrinsicContentSize
if let insets = padding {
contentSize.height += insets.top + insets.bottom
contentSize.width += insets.left + insets.right
}
return contentSize
}
}
}

Step 9: Press the login button, call the expansion method we created earlier

login button

@IBOutlet weak var txtPassword: UITextField!
@IBOutlet weak var txtUserName: UITextField!

//MARK: Login Action

@IBAction func btnLoginPressed(_ sender: UIButton) {
if txtUserName.text == ""
{
//Call UIView extension method
self.view.showToast(toastMessage: "Please Enter Username,beacuse it is necessary to add For getting logged in.", duration: 1.1)
}
else if txtPassword.text == ""
{
self.view.showToast(toastMessage: "Please Enter Password.", duration: 1.1)
}
else
{
//Do login
}

}

And done!

Frequently asked questions

Where can I use toast messages in iOS?

There are several use cases of toast messages. You can use them to view the consequences of actions triggered by your users. For example, you can notify a user upon successful login by displaying an iOS welcome message.

What is the difference between the iPhone app's toast message and the snack bar?

While a snack bar is similar to a quick toast, the only difference is that it is more versatile and interactive. For example, it allows users to undo actions with just one tap. A snack bar is commonly used to communicate feedback on user actions.

Can I view a toast message in Android?

Yes, you can view a toast message like the one shown here in an Android by following our instructions for displaying custom toast messages in your app using Android.

Conclusion

Now that you know how to display a toast message with animation in an iPhone app, you can play with different animations. For example, you can create an animation to lighten or lighten, run it in the reverse direction, or set it to repeat. When you are ready to move on to the next step in iPhone app development, you can start learning other components.

In the meantime, if you have an idea for iPhone app development and want to discuss it with us, you can send us a line with your app requirements. Our business analyst will contact you within 48 hours.

You may also like,

This page was last modified on 8 October 2020, at 10:57.

Do you want to develop a mobile app? Contact us now!

Get your free consultation now


Source link