Last active
May 18, 2017 07:05
-
-
Save anjnkmr/895cfcf9ec10f80b110f920b82314cb8 to your computer and use it in GitHub Desktop.
Simple iOS Toast
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var ak_toast_view_tag = 595; | |
var ak_toast_label_tag = 585; | |
extension UIWindow{ | |
func showToast(text: String){ | |
let v = getToastView(); | |
if v.superview != nil{ | |
v.removeFromSuperview(); | |
} | |
let label = getToastLabel(); | |
if label.superview == nil{ | |
v.addSubview(label); | |
} | |
let labelOldFrame = label.frame; | |
label.text = text; | |
label.sizeToFit(); | |
if labelOldFrame.width > label.frame.width{ | |
label.frame.size.width = labelOldFrame.width; | |
} | |
v.frame.size.height = label.frame.height + 20; | |
v.frame.origin.y = screenSize.height - v.frame.height - 55; | |
v.frame.origin.x = (screenSize.width - v.frame.width)/2; | |
v.alpha = 0; | |
self.addSubview(v); | |
UIView.animateWithDuration(0.4, animations: { | |
v.alpha = 0.8; | |
}) { (doned) in | |
UIView.animateWithDuration(0.4, delay: 2.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { | |
v.alpha = 0; | |
}, completion: { (doned2) in | |
v.removeFromSuperview(); | |
}) | |
} | |
} | |
func getToastView()->UIView{ | |
var v = self.viewWithTag(ak_toast_view_tag); | |
if v == nil{ | |
v = UIView(); | |
} | |
v!.tag = ak_toast_view_tag; | |
v!.frame = CGRectMake(10, screenSize.height - 80, screenSize.width - 40, 40); | |
v!.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(70); | |
v!.layer.cornerRadius = 20; | |
v!.clipsToBounds = true; | |
return v!; | |
} | |
func getToastLabel()->UILabel{ | |
var label: UILabel? = self.getToastView().viewWithTag(ak_toast_label_tag) as? UILabel; | |
if label == nil{ | |
label = UILabel(); | |
} | |
label!.tag = ak_toast_label_tag; | |
label!.textAlignment = .Center; | |
label!.numberOfLines = 0; | |
label!.font = UIFont.systemFontOfSize(14); | |
label!.frame = CGRectMake(5, 10, getToastView().frame.width - 10, 20); | |
label!.textColor = UIColor.whiteColor(); | |
return label!; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ViewController: UIViewController{ | |
func viewDidLoad(){ | |
let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate | |
appDelegate.window?.showToast("Hello world"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment