Swift Tutorial – How to Implement iOS Toast Message With Animation In Your iPhone App

0
Shares
Swift Tutorial – How to Implement iOS Toast Message With Animation In Your iPhone App
5 (100%) 1 vote

iOS Toast Message

Suppose you want to show some message for few seconds to notify your users upon a particular action, what method will you use? We’ve noticed many iPhone app developers use UIAlertView to achieve this goal. While UIAlertView is a good option to show some message, but the problem is, user will have to close the alert message manually.

Normally, it looks like this:

ios_alert_ok

Now what if you want to show the same message for some time and after that, the message should hide automatically?

iOS Toast Message is used for this purpose.

iOS Toast Message works similar to Android toast. If you’d like to learn how to implement Toast message in Android, read our Custom Android Toast Tutorial.

What is Toast Message ?

A toast message view is small, short-lived popup which provides a small bite of information to the users.

It looks something like this:

toast1

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

Let’s Get Started

In this demo, we’ll show Toast Alert with Blur animation when username or password field is left empty and user presses Login button.

Go to XCode and create new project.

demotoast1

Select project type as Single View Application and click on next.

demotoast2

In the next tab, set the project name and move forward.

demotoast3

Once you create a new project, go to Main.Storyboard, select ViewController and drop UITextField from “Show Object Library” section.

demotoast4

Now repeat this step for password as well.

Next, again go to Main.Storyboard, select ViewController and drop UIButton from “Show Object Library” section.

After adding the button, the final UI should look like this:

demotoast5

Once you’ve the UI ready similar to image above, it’s time to create an Event for login button.

demotoast6

Now, once you create the event, it’s time we implement the animation on toast.

demotoast7

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
}
}
}

On login button touch, call extension method which we created earlier.

demotoast8

@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!

Let’s run the demo and see the results.

What Next?

Play around with different animations in your iPhone app. For instance, you can make an animation to ease out or ease in, run it in reverse or set it to repeat. Once you feel ready to continue your journey towards next stage of iPhone app development, start learning other components.

Meanwhile, if you’ve an idea for mobile app and would like to discuss about cost estimation, drop us a line with your app requirements. Our business analyst will get back to you with accurate estimate within 24 hours.

 
0
Shares
 

Want to Develop a Mobile App? Contact Us Now!