iOS - Custom Confirmation view - ios

I am working on creating a custom control once user presses a button and action completes. I'm trying to replicate behavior of apple music app when album is added it shows confirmation view in center with a check mark as shown below. Are there any similar cocoa controls available to use?

(swift)
Create a singleton class
class CustomView: UIView {
class var sharedView : CustomView {
struct Static {
static var instance : CustomView?
static var token : dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = CustomView()
}
return Static.instance!
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func showInView(view:UIWindow) {
var image = UIImage(named:"SomeImage")
self.frame = view.frame
var originX = view.center.x
var originY = view.center.y
let centerView = UIImageView()
centerView.center = CGPointMake(originX, originY)
centerView.contentMode = UIViewContentMode.Center
centerView.image = image
centerView.alpha = 0
self.addSubview(centerView)
view.addSubview(self)
UIView.animateWithDuration(1, animations: { () -> Void in
centerView.alpha = 1
}) { (_) -> Void in
UIView.animateWithDuration(1, animations: { () -> Void in
centerView.frame.size = CGSizeMake(0,0)
centerView.alpha = 0
}) { (_) -> Void in
self.hide()
}
}
}
func hide()
{
if self.superview != nil
{
self.removeFromSuperview()
}
}
}
In your viewController you can just call the method CustomView.sharedView.showInView(view:UIApplication.sharedApplication.keyWindow())
Objective c .h
#import <UIKit/UIKit.h>
#interface CustomView : UIView
+ (instancetype)sharedInstance;
-(void)showInView:(UIWindow*)view;
#end
objective c .m
#import "CustomView.h"
#implementation CustomView
+ (instancetype)sharedInstance
{
static CustomView *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[CustomView alloc] init];
});
return sharedInstance;
}
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super initWithCoder:coder];
if (self) {
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
-(void)showInView:(UIWindow*)view {
UIImage *image = [UIImage imageNamed:#"img.png"];
self.frame = view.frame;
CGFloat originX = view.center.x;
CGFloat originY = view.center.y;
UIImageView *centerView = [UIImageView new];
centerView.center = CGPointMake(originX, originY);
centerView.contentMode = UIViewContentModeCenter;
centerView.image = image;
centerView.alpha = 0;
[self addSubview:centerView];
[view addSubview:self];
[UIView animateWithDuration:1 animations:^{
centerView.alpha = 1;
} completion:^(BOOL finished) {
[UIView animateWithDuration:1 animations:^{
centerView.frame = CGRectMake(originX, originY, 0, 0);
centerView.alpha = 0;
} completion:^(BOOL finished) {
[self hideView];
}];
}];
}
-(void)hideView {
if(self.superview) {
[self removeFromSuperview];
}
}
#end
Import CustomView.h in your file and
[[CustomView sharedInstance] showInView:[[UIApplication sharedApplication]keyWindow]];

Related

Adding NSTimer in image slide and page contol to move images automatically

Here is the image slider works fine when dragging manually the image changes with page control indicator change but I want to add the timer to the following code and move the images and indicator automatically. Please help me to apply NS timer in this code and also want to move from the last image to 1st image and so on.
#implementation DashboardViewController {
NSArray * animationArray;
}
#synthesize scroller = scroller;
#synthesize pageControl = pageControl;
-(void) viewDidLoad {
[super viewDidLoad];
scroller.pagingEnabled = YES;
scroller.showsHorizontalScrollIndicator = NO;
scroller.delegate = self;
animationArray = [NSArray arrayWithObjects: [UIImage imageNamed: # "image1.jpg"],
[UIImage imageNamed: # "image2.jpg"],
[UIImage imageNamed: # "image3.jpg"],
[UIImage imageNamed: # "image4.png"],
[UIImage imageNamed: # "image5.jpg"],
nil
];
CGRect scrollFrame = CGRectMake(0, 0, self.view.frame.size.width, self.scroller.frame.size.height);
scroller.frame = scrollFrame;
self.scroller.contentSize = CGSizeMake(self.scroller.frame.size.width * animationArray.count, self.scroller.frame.size.height);
for (int i = 0; i < animationArray.count; i++) {
CGRect frame;
frame.origin.x = self.scroller.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.scroller.frame.size;
UIImageView * imgView = [
[UIImageView alloc] initWithFrame: CGRectMake(self.scroller.frame.size.width * i, 0, self.scroller.frame.size.width, self.scroller.frame.size.height)
];
imgView.image = [animationArray objectAtIndex: i];
imgView.frame = frame;
[self.scroller addSubview: imgView];
}
self.pageControl.currentPage = 0;
}
-(void) scrollViewDidScroll: (UIScrollView * ) sender {
if (!pageControlBeingUsed) {
// Switch the indicator when more than 50% of the previous/next page is visible
CGFloat pageWidth = self.scroller.frame.size.width;
int page = floor((self.scroller.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
self.pageControl.currentPage = page;
}
}
-(void) scrollViewWillBeginDragging: (UIScrollView * ) scrollView {
pageControlBeingUsed = NO;
}
-(void) scrollViewDidEndDecelerating: (UIScrollView * ) scrollView {
[self setIndiactorForCurrentPage];
}
-(void) setIndiactorForCurrentPage {
uint page = scroller.contentOffset.x / scroller.frame.size.width;
[pageControl setCurrentPage: page];
}
- (IBAction) changePage {
// Update the scroll view to the appropriate page
CGRect frame;
pageControl.currentPage = animationArray.count;
frame.origin.x = self.scroller.frame.size.width * self.pageControl.currentPage;
frame.origin.y = 0;
frame.size = self.scroller.frame.size;
[self.scroller scrollRectToVisible: frame animated: YES];
pageControlBeingUsed = YES;
}
- (void) didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
self.scroller = nil;
self.pageControl = nil;
}
Please try this code for NSTimer (i use collectionView for easy use)
var timer : Timer?
var currentFeaturedCouponIndex = 0
//MARK: - NSTimer -
func setupTimer(){
timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(self.scrollFeatured), userInfo: nil, repeats: true);
}
func scrollFeatured(){
if self.arrFeaturedCoupon.count > 0 {
//Becauese we scroll coupon if total is > 1
if self.arrFeaturedCoupon.count > 1 {
if self.currentFeaturedCouponIndex < self.arrFeaturedCoupon.count - 1 {
self.currentFeaturedCouponIndex = self.currentFeaturedCouponIndex + 1
}
else {
self.currentFeaturedCouponIndex = 0
}
self.pageControl.currentPage = currentFeaturedCouponIndex
//When currentFeaturedCouponIndex == 0 we make animated: false
if self.currentFeaturedCouponIndex == 0 {
self.featuredCouponColView.scrollToItem(at: self.featuredCouponCurrentIndexPath, at: UICollectionViewScrollPosition.left, animated: false)
}
else {
self.featuredCouponColView.scrollToItem(at: self.featuredCouponCurrentIndexPath, at: UICollectionViewScrollPosition.left, animated: true)
}
}
}
}
To invalidate timer when and where you want
func invalidateTimer(){
if timer != nil {
self.timer!.invalidate()
self.timer = nil
}
}

UISearchController with loading indicator

I implemented UISearchController and I'm getting the data from a js callback but when I tape in the searchbar it takes some time to put the data so I wanted to know how to implement a loading indicator into the table view result of UISearchController
Wrote this extension in Swift 3, which seems to work pretty well.
extension UISearchBar {
private var textField: UITextField? {
return subviews.first?.subviews.flatMap { $0 as? UITextField }.first
}
private var activityIndicator: UIActivityIndicatorView? {
return textField?.leftView?.subviews.flatMap{ $0 as? UIActivityIndicatorView }.first
}
var isLoading: Bool {
get {
return activityIndicator != nil
} set {
if newValue {
if activityIndicator == nil {
let newActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
newActivityIndicator.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
newActivityIndicator.startAnimating()
newActivityIndicator.backgroundColor = UIColor.white
textField?.leftView?.addSubview(newActivityIndicator)
let leftViewSize = textField?.leftView?.frame.size ?? CGSize.zero
newActivityIndicator.center = CGPoint(x: leftViewSize.width/2, y: leftViewSize.height/2)
}
} else {
activityIndicator?.removeFromSuperview()
}
}
}
}
Loading indicator on search results controller
Updated solution for iOS 13:
extension UISearchBar {
var textField: UITextField? {
if #available(iOS 13.0, *) {
return searchTextField
} else {
if let textField = value(forKey: "searchField") as? UITextField {
return textField
}
return nil
}
}
private var activityIndicator: UIActivityIndicatorView? {
return textField?.leftView?.subviews.compactMap{ $0 as? UIActivityIndicatorView }.first
}
var isLoading: Bool {
get {
return activityIndicator != nil
} set {
if newValue {
if activityIndicator == nil {
let newActivityIndicator = UIActivityIndicatorView(style: .gray)
newActivityIndicator.startAnimating()
if #available(iOS 13.0, *) {
newActivityIndicator.backgroundColor = UIColor.systemGroupedBackground
} else {
newActivityIndicator.backgroundColor = UIColor.groupTableViewBackground
}
newActivityIndicator.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
textField?.leftView?.addSubview(newActivityIndicator)
let leftViewSize = textField?.leftView?.frame.size ?? CGSize.zero
newActivityIndicator.center = CGPoint(x: leftViewSize.width/2, y: leftViewSize.height/2)
}
} else {
activityIndicator?.removeFromSuperview()
}
}
}
}
When you start searching at that time you can create an activity indicator and add it as the subview of UISearchBar using addSubView method.
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
//set your frame for activity indicator
[searchBar addSubview: spinner];
[spinner startAnimating];
When you finish the search remove it from the search bar using removeFromSuperView method.
Please try this one. May be its helpfull to you
SearchBarWithloading.h
#import <UIKit/UIKit.h>
#interface SearchBarWithloading : UISearchBar
- (void)startActivity; // increments startCount and shows activity indicator
- (void)finishActivity; // decrements startCount and hides activity indicator if 0
#end
SearchBarWithloading.m
import "SearchBarWithloading.h"
#interface SearchBarWithloading()
#property(nonatomic) UIActivityIndicatorView *activityIndicatorView;
#property(nonatomic) int startCount;
#end
#implementation SearchBarWithloading
- (void)layoutSubviews {
UITextField *searchField = nil;
for(UIView* view in self.subviews){
if([view isKindOfClass:[UITextField class]]){
searchField= (UITextField *)view;
break;
}
}
if(searchField) {
if (!self.activityIndicatorView) {
UIActivityIndicatorView *taiv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
taiv.center = CGPointMake(searchField.leftView.bounds.origin.x + searchField.leftView.bounds.size.width/2,
searchField.leftView.bounds.origin.y + searchField.leftView.bounds.size.height/2);
taiv.hidesWhenStopped = YES;
taiv.backgroundColor = [UIColor whiteColor];
self.activityIndicatorView = taiv;
[taiv release];
_startCount = 0;
[searchField.leftView addSubview:self.activityIndicatorView];
}
}
[super layoutSubviews];
}
- (void)startActivity {
self.startCount = self.startCount + 1;
}
- (void)finishActivity {
self.startCount = self.startCount - 1;
}
- (void)setStartCount:(int)startCount {
_startCount = startCount;
if (_startCount > 0)
[self.activityIndicatorView startAnimating];
else {
[self.activityIndicatorView stopAnimating];
}
}
#end
A cleaner solution for iOS 13 and above:
extension UISearchController {
private static let defaultLeftView: UIView = {
UISearchTextField().leftView ?? UIView()
}()
private static let leftViewSize: CGSize = {
UISearchTextField().leftView?.frame.size ?? .zero
}()
private static let loadingLeftView: UIView = {
let view = UIView(frame: .init(origin: .zero, size: leftViewSize))
let activityIndicatorView = UIActivityIndicatorView(style: .medium)
activityIndicatorView.transform = .init(scaleX: 0.9, y: 0.9)
activityIndicatorView.startAnimating()
view.addSubview(activityIndicatorView)
activityIndicatorView.center = CGPoint(x: leftViewSize.width / 2, y: leftViewSize.height / 2)
return view
}()
func startLoading() {
searchBar.searchTextField.leftView = Self.loadingLeftView
}
func stopLoading() {
searchBar.searchTextField.leftView = Self.defaultLeftView
}
}

how to create property method in swift

I make one UITableView property in my class and make getter method for it like this:
#interface SideViewController : UIViewController <UITableViewDataSource,UITableViewDelegate>
#property (nonatomic,strong) UITableView *table;
#end
#implementation SideViewController
#synthesize selectedIndex;
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor redColor];
}
- (UITableView*)table {
if (!_table) {
CGRect tableFrame = CGRectMake(0,150,230, self.view.frame.size.height-150);
_table = [[UITableView alloc]initWithFrame:tableFrame style:UITableViewStylePlain];
_table.scrollEnabled = NO;
_table.delegate = self;
_table.dataSource = self;
_table.showsVerticalScrollIndicator = YES;
_table.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
[_table setBackgroundColor:[UIColor clearColor]];
_table.separatorStyle = UITableViewCellSeparatorStyleNone;
}
return _table;
}
when I call self.table get my table now I want write this code in swift but I'm so confused!!!
please guide me about that.
this is my swift code :
import UIKit
class SideViewController: UIViewController,UITableViewDelegate {
let table:UITableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.redColor()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You can use lazy in swift:
class SideViewController: UIViewController, UITableViewDelegate {
lazy var table: UITableView = {
let tableFrame = CGRectMake(0, 150, 230, self.view.frame.size.height - 150)
let _table = UITableView(frame: tableFrame, style: UITableViewStyle.Plain)
_table.scrollEnabled = false
_table.delegate = self
_table.dataSource = self
_table.showsVerticalScrollIndicator = true
_table.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
_table.backgroundColor = UIColor.clearColor()
_table.separatorStyle = UITableViewCellSeparatorStyle.None
return _table
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.redColor()
}
}

Add shade gradient to the bottom of a uitableviewcell / uiimageview

Does anyone know how add a gradient to the bottom of a uitableviewcell or the uiimageview like the image shown below does?
Add this class into your project (swift):
class UIGradientImageView: UIImageView {
let myGradientLayer: CAGradientLayer
override init?(frame: CGRect){
myGradientLayer = CAGradientLayer()
super.init(frame: frame)
self.setup()
addGradientLayer()
}
func addGradientLayer(){
if myGradientLayer.superlayer == nil{
self.layer.addSublayer(myGradientLayer)
}
}
required init(coder aDecoder: NSCoder){
myGradientLayer = CAGradientLayer()
super.init(coder: aDecoder)
self.setup()
addGradientLayer()
}
func getColors() -> [CGColorRef] {
return [UIColor.clearColor().CGColor, UIColor(red: 0, green: 0, blue: 0, alpha: 0.5).CGColor]
}
func getLocations() -> [CGFloat]{
return [0.5, 0.9]
}
func setup() {
myGradientLayer.startPoint = CGPoint(x: 0.5, y: 0)
myGradientLayer.endPoint = CGPoint(x: 0.5, y: 1)
let colors = getColors()
myGradientLayer.colors = colors
myGradientLayer.opaque = false
myGradientLayer.locations = getLocations()
}
override func layoutSubviews() {
super.layoutSubviews()
myGradientLayer.frame = self.layer.bounds
}
}
UPDATE: Objective-C translated solution. Credits to #SleepsOnNewspapers.
#import "UIGradientImageView.h"
#interface UIGradientImageView()
#property (nonatomic, strong) CAGradientLayer *myGradientLayer;
#end
#implementation UIGradientImageView
-(instancetype)initWithFrame:(CGRect)frame{
if(self){
self = [super initWithFrame:frame];
self.myGradientLayer = [[CAGradientLayer alloc]init];
[self setup];
[self addGradientLayer];
}
return self;
}
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
if(self){
self = [super initWithCoder:aDecoder];
self.myGradientLayer = [[CAGradientLayer alloc]init];
[self setup];
[self addGradientLayer];
}
return self;
}
-(void)addGradientLayer{
if (self.myGradientLayer.superlayer == nil) {
[self.layer addSublayer:self.myGradientLayer];
}
}
Make your UIImageView class on your storyboard to be this one instead of default.

What is the android.widget.Toast equivalent for iOS applications?

I have made Android application a few months ago. The Toast class is very useful for me.
I do not need to consider the main Thread and place to show it. Anywhere I can show it and just leave that and it is automatically disappeared.
Toast.makeToast(context, msg, Toast.LENGTH_SHORT).show();
That's it. ^^
What about iPhone? Is there something like the Toast? Just show message and do not need to care about it. It will be automatically disappeared.
I've been writing for Android for a long time and I am missing Toast. I've implemented one. Need code? here you are:
ToastView.h
#import <UIKit/UIKit.h>
#interface ToastView : UIView
#property (strong, nonatomic) NSString *text;
+ (void)showToastInParentView: (UIView *)parentView withText:(NSString *)text withDuaration:(float)duration;
#end
ToastView.m
#import "ToastView.h"
#interface ToastView ()
#property (strong, nonatomic, readonly) UILabel *textLabel;
#end
#implementation ToastView
#synthesize textLabel = _textLabel;
float const ToastHeight = 50.0f;
float const ToastGap = 10.0f;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
-(UILabel *)textLabel
{
if (!_textLabel) {
_textLabel = [[UILabel alloc] initWithFrame:CGRectMake(5.0, 5.0, self.frame.size.width - 10.0, self.frame.size.height - 10.0)];
_textLabel.backgroundColor = [UIColor clearColor];
_textLabel.textAlignment = NSTextAlignmentCenter;
_textLabel.textColor = [UIColor whiteColor];
_textLabel.numberOfLines = 2;
_textLabel.font = [UIFont systemFontOfSize:13.0];
_textLabel.lineBreakMode = NSLineBreakByCharWrapping;
[self addSubview:_textLabel];
}
return _textLabel;
}
- (void)setText:(NSString *)text
{
_text = text;
self.textLabel.text = text;
}
+ (void)showToastInParentView: (UIView *)parentView withText:(NSString *)text withDuaration:(float)duration;
{
//Count toast views are already showing on parent. Made to show several toasts one above another
int toastsAlreadyInParent = 0;
for (UIView *subView in [parentView subviews]) {
if ([subView isKindOfClass:[ToastView class]])
{
toastsAlreadyInParent++;
}
}
CGRect parentFrame = parentView.frame;
float yOrigin = parentFrame.size.height - (70.0 + ToastHeight * toastsAlreadyInParent + ToastGap * toastsAlreadyInParent);
CGRect selfFrame = CGRectMake(parentFrame.origin.x + 20.0, yOrigin, parentFrame.size.width - 40.0, ToastHeight);
ToastView *toast = [[ToastView alloc] initWithFrame:selfFrame];
toast.backgroundColor = [UIColor darkGrayColor];
toast.alpha = 0.0f;
toast.layer.cornerRadius = 4.0;
toast.text = text;
[parentView addSubview:toast];
[UIView animateWithDuration:0.4 animations:^{
toast.alpha = 0.9f;
toast.textLabel.alpha = 0.9f;
}completion:^(BOOL finished) {
if(finished){
}
}];
[toast performSelector:#selector(hideSelf) withObject:nil afterDelay:duration];
}
- (void)hideSelf
{
[UIView animateWithDuration:0.4 animations:^{
self.alpha = 0.0;
self.textLabel.alpha = 0.0;
}completion:^(BOOL finished) {
if(finished){
[self removeFromSuperview];
}
}];
}
#end
Call from ViewController
[ToastView showToastInParentView:self.view withText:#"What a toast!" withDuaration:5.0];
There is no class "out-of-the-box" in UIKit to do this. But it is quite easy to create a class that will offer this behavior.
You just have to create a class that inherit from UIView. This class will have the responsibility
- to create what you want to display,
- to add itself in parent view hierarchy
- to dismiss itself using a timer.
You will be able to use it like :
[ToastView toastViewInView:myParentView withText:#"what a wonderful text"];
Regards,
Quentin
Have not tried but you might want to check:
https://github.com/ecstasy2/toast-notifications-ios
https://github.com/scalessec/Toast
You can do this in many ways one of the way is using UIAlertViewController() in swift3
let alertManager=UIAlertController(title: nil, message: "Welcome!", preferredStyle: .alert)
self.present(alertManager, animated: true, completion: nil)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1,
execute: {
alertManager.dismiss(animated: false, completion: nil)
})
Edit: Updated for Swift 3
Here is a Swift 3 version based on wojciech_maciejewski's answer. This looks more like Android Toast and doesn't stack toasts on each other. It draws toast into the center of the screen. It can handle long multiline texts.
import UIKit
class ToastView: UIView {
private static let hLabelGap: CGFloat = 40.0
private static let vLabelGap: CGFloat = 20.0
private static let hToastGap: CGFloat = 20.0
private static let vToastGap: CGFloat = 10.0
private var textLabel: UILabel!
static func showInParent(_ parentView: UIView, _ text: String, duration: Double = 3.0) {
let labelFrame = CGRect(x: parentView.frame.origin.x + hLabelGap,
y: parentView.frame.origin.y + vLabelGap,
width: parentView.frame.width - 2 * hLabelGap,
height: parentView.frame.height - 2 * vLabelGap)
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 15.0)
label.text = text
label.backgroundColor = UIColor.clear
label.textAlignment = NSTextAlignment.center
label.textColor = UIColor.white
label.numberOfLines = 0
label.frame = labelFrame
label.sizeToFit()
let toast = ToastView()
toast.textLabel = label
toast.addSubview(label)
toast.frame = CGRect(x: label.frame.origin.x - hToastGap,
y: label.frame.origin.y - vToastGap,
width: label.frame.width + 2 * hToastGap,
height: label.frame.height + 2 * vToastGap)
toast.backgroundColor = UIColor.darkGray
toast.alpha = 0.0
toast.layer.cornerRadius = 20.0
toast.center = parentView.center
label.center = CGPoint(x: toast.frame.size.width / 2, y: toast.frame.size.height / 2)
parentView.addSubview(toast)
UIView.animate(withDuration: 0.4, animations: {
toast.alpha = 0.9
label.alpha = 0.9
})
toast.perform(#selector(hideSelf), with: nil, afterDelay: duration)
}
#objc private func hideSelf() {
UIView.animate(withDuration: 0.4, animations: {
self.alpha = 0.0
self.textLabel.alpha = 0.0
}, completion: { t in self.removeFromSuperview() })
}
}
Usage from another controller:
ToastView.showInParent(navigationController!.view, "Hello world")
I'm posting swift version of Scarmysun answer:) many thanks
import Foundation
import UIKit
class ToastView: UIView {
static let toastHeight:CGFloat = 50.0
static let toastGap:CGFloat = 10;
lazy var textLabel: UILabel = UILabel(frame: CGRectMake(5.0, 5.0, self.frame.size.width - 10.0, self.frame.size.height - 10.0))
static func showInParent(parentView: UIView!, withText text: String, forDuration duration: double_t) {
//Count toast views are already showing on parent. Made to show several toasts one above another
var toastsAlreadyInParent = 0;
for view in parentView.subviews {
if (view.isKindOfClass(ToastView)) {
toastsAlreadyInParent++
}
}
var parentFrame = parentView.frame;
var yOrigin = parentFrame.size.height - getDouble(toastsAlreadyInParent)
var selfFrame = CGRectMake(parentFrame.origin.x + 20.0, yOrigin, parentFrame.size.width - 40.0, toastHeight);
var toast = ToastView(frame: selfFrame)
toast.textLabel.backgroundColor = UIColor.clearColor()
toast.textLabel.textAlignment = NSTextAlignment.Center
toast.textLabel.textColor = UIColor.whiteColor()
toast.textLabel.numberOfLines = 2
toast.textLabel.font = UIFont.systemFontOfSize(13.0)
toast.addSubview(toast.textLabel)
toast.backgroundColor = UIColor.darkGrayColor()
toast.alpha = 0.0;
toast.layer.cornerRadius = 4.0;
toast.textLabel.text = text;
parentView.addSubview(toast)
UIView.animateWithDuration(0.4, animations: {
toast.alpha = 0.9
toast.textLabel.alpha = 0.9
})
toast.performSelector(Selector("hideSelf"), withObject: nil, afterDelay: duration)
}
static private func getDouble(toastsAlreadyInParent : Int) -> CGFloat {
return (70.0 + toastHeight * CGFloat(toastsAlreadyInParent) + toastGap * CGFloat(toastsAlreadyInParent));
}
func hideSelf() {
UIView.animateWithDuration(0.4, animations: {
self.alpha = 0.0
self.textLabel.alpha = 0.0
}, completion: { t in self.removeFromSuperview() })
}
}

Resources