Create Loading View in Objective C

today we are doing how to create Loading View in objective C .

Purpose Of Loading view

if you are request for calling Web-services then it takes a time to get response. So what to do until not getting response ??? yes stop user interaction in whole screen until not get web-service response.!!

Create Loading View

create one view with the size of window with clear color and add sub view with whatever you like to display loading view to user (NoT: Set view with Stop user Interaction while you are displaying Loading View )

method for Show Loading view To user

-(void)showLoadingView
{
    
    if (loadView == nil) {
		loadView = [[UIView alloc] initWithFrame:self.window.frame];
        loadView.opaque = NO;
        loadView.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.3];
        
        CGRect windowFrm =self.window.frame;
        
        viewBack = [[UIView alloc] initWithFrame:CGRectMake(windowFrm.size.width/2 -65 , windowFrm.size.height/2 -20, 130, 40)];
        viewBack.backgroundColor = [UIColor blackColor];
        viewBack.alpha = 0.7f;
        viewBack.tag = 999;
        viewBack.layer.masksToBounds = NO;
        viewBack.layer.cornerRadius = 2;
        
        spinningWheel = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(10.0, 10.0, 20.0, 20.0)];
        spinningWheel.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
        [spinningWheel startAnimating];
        [viewBack addSubview:spinningWheel];
        
        UILabel *lblLoading = [[UILabel alloc] initWithFrame:CGRectMake(23, 5, 100, 25)];
        lblLoading.text = @"Loading...";
        lblLoading.backgroundColor = [UIColor clearColor];
        lblLoading.font = [UIFont systemFontOfSize:17.0f];
        lblLoading.textAlignment = NSTextAlignmentCenter;
        lblLoading.textColor = [UIColor whiteColor];
        
        [viewBack addSubview:lblLoading];
        [loadView addSubview:viewBack];
    }
    [self.window addSubview:loadView];
}

method for Hide Loading View from the screen

-(void)hideLoadingView
{
    [loadView removeFromSuperview];
    loadView = nil;
}


Preview Screen while Loading

iOS Simulator Screen shot 05-Oct-2014 1.46.12 pm

you can download demo programs From here

you can download demo programs From here

Working With NSNotificationCenter in Objective-C

Today we are learnign how to do work with notificationcenter So lest start

NSNotificationCenter provides a centralized hub through which any part of an application may notify and be notified of changes from any other part of the application. Observers register with a notification center to respond to particular events with a specified action. Each time an event occurs, the notification goes through its dispatch table, and messages any registered observers for that event. (Note: Each running Cocoa program manages its own default notification center, so it’s unusual for a new notification center to be instantiated separately.)

Each NSNotification object has a name, with additional context optionally provided by an associated object and userInfo dictionary.
For example, UITextField posts an NSNotification with the name UITextFieldTextDidChangeNotification each time its text changes. The object associated with that notification is the text field itself. In the case of UIKeyboardWillShowNotification, frame positioning and animation timing are passed in userInfo, while the notification’s associated object is nil.

Notifications classes

Foundation provides 3 classes to deal with all your notification

  • NSNotification: represents a notification.
  • NSNotificationCenter: broadcasts notifications and manages observers. Each app has a default notification center via defaultCenter.
  • NSNotificationQueue: coalesces and delays notifications. Each thread has a default notification queue via defaultQueue.

OS X offers a fourth class called NSDistributedNotificationCenter for communication between processes.

Receiving notifications

To receive a notification you only need to know its name. Cocoa and Cocoa Touch are full of interesting and descriptively named notifications such as UIKeyboardWillShowNotification and UIApplicationDidReceiveMemoryWarningNotification.

- (id) init {
    if (self = [super init]) {
        _cache = [[NSCache alloc] init];
        [[NSNotificationCenter defaultCenter] addObserver:self
            selector:@selector(applicationDidReceiveMemoryWarning:)
            name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
    }
    return self;
}
 
- (void) applicationDidReceiveMemoryWarning:(NSNotification*)notification {
    [_cache removeAllObjects];
}
 
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self
        name:UIApplicationDidReceiveMemoryWarningNotification];
}

Handling the notification

Observers will receive notifications until they are removed from the NSNotificationCenter. Each notification is sent once per addObserver call. If you are receiving more notifications than expected, it might be a sign that you added the observer more than once (e.g., this might happen if you register the observer for notifications in viewWillAppear and unregister it in dealloc).
NSNotificationCenter will call the selector provided in addObserver:selector:name:object: with a single argument of type NSNotification. The selector is called in the same thread in which the notification was posted. Typically this is the main thread, so only check if the selector is running in a different thread if the corresponding documentation says otherwise.

- (void) moviePlayerPlaybackDidFinish:(NSNotification*)notification {
    MPMoviePlayerController *mpObject = (MPMoviePlayerController *) notification.object; 
    NSDictionary *userInfo = notification userInfo;
    MPMovieFinishReason reason = [[userInfo objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey] intValue];
}

Knowing the contents of this dictionary for a specific notification might require debugging or -god forbid- reading the documentation. Don’t assume that any particular key will be present unless told otherwise.

- (id) init {
    if (self = [super init]) {
        _cache = [[NSCache alloc] init];
        _observer = [[NSNotificationCenter defaultCenter]
            addObserverForName:UIApplicationDidReceiveMemoryWarningNotification 
            object:nil
            queue:nil
            usingBlock:^(NSNotification *notification) {
                [_cache removeAllObjects];
            }
        ];
    }
    return self;
}
 
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:_observer
        name:UIApplicationDidReceiveMemoryWarningNotification];
}

Sending synchronous notifications

Notifications are great to broadcast events that might be of general interest, such as model changes, user actions or the status of background processes. Unlike the delegate pattern, notifications can be used to notify various stakeholders and add very little coupling (in most cases, the observer only needs to know the notification name).

Posting the notification

Each app has a default NSNotificationCenter instance that can be used to broadcast notifications. You can create the notification object yourself and post it, or use a couple of convenience methods that do this. If you don’t need to send any additional information, posting a notification is as simple as:

[[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:notificationSender];

Sending additional information

In most cases you will want to send additional information with the notification, such as the progress value in the example above. Notifications can have a dictionary with custom data called userInfo. NSNotifcationCenter offers a convenience method to post notifications with userInfo:

NSDictionary *userInfo = @{@"someKey": someValue};
[[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:notificationSender userInfo:userInfo];

Download demo program from  here

How to Create own Custom Flat Button in Objective C

hello Every one Today We are leaning how to create lovely custom flat buttons..

if you are working on projects or a big apps than you have to maintain the theme of the whole application for example Application color , navigations icons buttons and many more.. how can we handle that ?? using Customization !!!

so lets create Custom Buttons For our Application like this

 iOS Simulator Screen Shot 31-Aug-2014 2.32.53 pm

so lets start the Code

Step 1: Create new Project with single view Application and add one view Controller as root view in appDelegate

step 2: for Button class create new File and do subclass of “UIButton” and give name as “MBButton” as you can see in below screen.

Screen Shot 2014-08-31 at 2.42.03 pm

step 3) in your Custom Button Class MBButton.h set enum for your button Types for example :

 

typedef NS_ENUM(NSInteger, MBButtonType) {
    ButtonDefault= 0,
    ButtonCircle
};

and your private varible for the class as below

    MBButtonType buttonType;
    NSString *buttonTitle;
    CGRect buttonFrame;

and add one methods for your Button Frame

-(id)initWithFrame:(CGRect)frame type:(MBButtonType)btnType;

now add define your Button Colors as your theme forExample

   #define Custom_Gray [UIColor colorWithRed:(210.0f/255.0f) green:(210.0f/255.0f) blue:(210.0f/255.0f) alpha:1.0f]
   #define Custom_Green [UIColor colorWithRed:(99.0f/255.0f) green:(181.0f/255.0f) blue:(76.0f/255.0f) alpha:1.0f]
   #define Custom_Green_Dark [UIColor colorWithRed:(75.0f/255.0f) green:(175.0f/255.0f) blue:(50.0f/255.0f) alpha:1.0f]

Step 4) in MBButton.m file

in MBButton.m file write code for the button frame methods

-(id)initWithFrame:(CGRect)frame type:(MBButtonType)btnType
{
    self = [super initWithFrame:frame];
    buttonFrame = frame;
    if(self ){
        buttonType  = btnType;
        [self setButtonWithType];     // set Button theme as per button type
        if(buttonType == ButtonCircle){
            // set Frame size for circle
            if(frame.size.height > frame.size.width){
                buttonFrame.size.height = frame.size.width;
            }else {
                buttonFrame.size.width = frame.size.height;
            }
       }
    }
    return  self;
}

write code for individual button Types

/* SET BUTTON */
-(void)setButtonWithType
{
    switch (buttonType) {
        case ButtonDefault:
            [self setBackgroundImage:[self createImageFromColor:Custom_Gray] forState:UIControlStateNormal];
            [self setBackgroundImage:[self createImageFromColor:Custom_Gray] forState:UIControlStateHighlighted];
            [self setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            self.layer.borderColor = [UIColor grayColor].CGColor;
            self.layer.borderWidth = 0.0f;
            self.layer.cornerRadius = 4.0f;
            break;
            
        case ButtonCircle:
            [self setBackgroundImage:[self createImageFromColor: Custom_Green] forState:UIControlStateNormal];
            [self setBackgroundImage:[self createImageFromColor:Custom_Green_Dark] forState:UIControlStateHighlighted];
            [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            self.layer.borderColor = [UIColor blackColor].CGColor;
            self.layer.borderWidth = 0.0f;
            self.layer.cornerRadius = self.frame.size.width/2;
            
            break;
        default:
            break;
    }
    
    gesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap:)];
    gesture.numberOfTapsRequired =1;
    [self addGestureRecognizer:gesture];
    self.layer.masksToBounds = YES;
}

Handle The Tap of the Buttons

-(void)handleTap:(id)sender {
    
    CATransition *animation = [CATransition animation];
    [animation setDelegate:self];
    [animation setDuration:1.0f];
    [animation setTimingFunction:UIViewAnimationCurveEaseInOut];
    [animation setType:@"rippleEffect" ];
    [self.layer addAnimation:animation forKey:NULL];
}

create Image for the Colors

/* CREATE IMAGE FROM THE COLOR */
-(UIImage *)createImageFromColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

Now your custom button ready to use 🙂

just import the

 #import "MBButton.h"

in your ViewController and write bellow code

    MBButton *button = [[MBButton alloc]initWithFrame:CGRectMake(100, 100, 100, 40) type:ButtonDefault];
    [button setTitle:@"Default" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(onClickDefaultButton) forControlEvents:UIControlEventTouchUpInside];
-(void)onClickDefaultButton
{
    NSLog(@"Button Click Default");
}

Yeah i Done it.!!!

 

simulatorRecod

You Can download also Code From Here