Pages

Thursday, January 31, 2013

Show / Hide Status bar in iOS or Make Full Screen App

1. Click Your Project name in left top
2. Now Click the Target for this Project
3. Now in Summary iPhone/iPad Deployment Info > Click the check box on or off for Status Bar Visibility.

Thats it :)

Add Multiple Screens with Slide Effect in xCode + UINavigation

Follow the Steps below for this.

Step 1. Create New Application then Empty Application
 - It will create applicationname.h and applicationname.m file inside your project

Step 2. Create New File> Cocoa Touch> Objective-C Class 
 - It will create newFileName.xib file with oits class Files (.h and .m)

Step 3. Take Subclass of UIViewController for this
 - Click the checkbox of "With XIB for user interface" - Lets Suppose Its Name is LoginViewController

Step 4. Create or Drop a Button inside xib file to load the next View

Step 5. Now go to AppDelegate.h file and add

@property (strong, nonatomic) UINavigationController *navigation;

Step 6. Now go to AppDelegate.m file and add Code 
 - Import your xib file class in AppDelegate.m file

#import "LoginViewController.h"

 - Then add the following code as mentioned in below function 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];

    //********************* Add the Following Code *********************//
    LoginViewController *loginView = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
    self.navigation = [[UINavigationController alloc] initWithRootViewController:loginView];
    //[self.window addSubview:self.navigation.view]; // This is for Non Rotation
    [self.window setRootViewController:self.navigation]; // This is proper way to make the orientation as well
    //********************* Up to Here Code *********************//

    [self.window makeKeyAndVisible];
    return YES;
}

Step 7. If you want to hide the default Navigation by xCode then go to LoginViewController.m

and add following line in -(void)viewDidLoad

[self.navigationController setNavigationBarHidden:YES animated:YES];

Step 8. Now Create a new Obejctive C Class from Cocoa Touch and Give any name ( i have taken name as - TabsViewController

Step 9. Now go again to LoginViewControll.m (First Class File)
 - Import the Second Class you have made in this
#import "TabsViewController.h"

 - Now Made a function in LoginViewControll.m as below.

// This is basically a button Action function, which is declared in LoginViewController.h file. You can See many samples in google to make this linking


- (IBAction)loginContinueAction:(id)sender {
    TabsViewController *tabs = [[TabsViewController alloc] init];
    [self.navigationController pushViewController:tabs animated:YES];
}

So Here You are, You have New View after clicking the button :)

Just do the same steps from Step 8 to create new Views one after another.




If you are Working for sdk 4.6 and siulator 6.1 then you must need to work with storyboard. Easy to use and easy to handle.

For StoryBoard: http://varunxcode.blogspot.in/2013/09/appear-and-disappear-multiple-view.html

Reference: https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/UsingViewControllersinYourApplication/UsingViewControllersinYourApplication.html

Simple Drag Drop with Zoom and Rotate in xCode

Today i am very happy to put this Post as This is the heart of iPhone/iPod/iPad main event. i.e. Zooming Image or Rotating it.

You just need to follow the main thing as below.
1. Put your any View component inside a UIScrollView. You can do this by following code.

//Make a simple view
UIScrollView *viewForImage = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
[viewForImage addSubview:imageView];

in above code "imageView" is my runtime UIImageView. (You can put your view component here)

2. Now inherit UIGestureRecognizerDelegate in your class ".h" file as below.


@interface SecondTabViewController :  UIViewController < UIGestureRecognizerDelegate>

3. Now add your every UIScrollView for Gesture Recognizer as follow.


[self addGestureRecognizersToPiece:viewForImage];

4. Now Just copy paste the below method in your class ".m" as this code is from Apple itself.


// adds a set of gesture recognizers to one of our piece subviews
- (void)addGestureRecognizersToPiece:(UIView *)piece
{
    UIRotationGestureRecognizer *rotationGesture = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotatePiece:)];
    [piece addGestureRecognizer:rotationGesture];
    
    UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(scalePiece:)];
    [pinchGesture setDelegate:self];
    [piece addGestureRecognizer:pinchGesture];
    
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panPiece:)];
    [panGesture setMaximumNumberOfTouches:2];
    [panGesture setDelegate:self];
    [piece addGestureRecognizer:panGesture];
}

- (void)panPiece:(UIPanGestureRecognizer *)gestureRecognizer
{
    UIView *piece = [gestureRecognizer view];
    
    [self adjustAnchorPointForGestureRecognizer:gestureRecognizer];
    
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
        CGPoint translation = [gestureRecognizer translationInView:[piece superview]];
        
        [piece setCenter:CGPointMake([piece center].x + translation.x, [piece center].y + translation.y)];
        [gestureRecognizer setTranslation:CGPointZero inView:[piece superview]];
    }
}

// rotate the piece by the current rotation
// reset the gesture recognizer's rotation to 0 after applying so the next callback is a delta from the current rotation
- (void)rotatePiece:(UIRotationGestureRecognizer *)gestureRecognizer
{
    [self adjustAnchorPointForGestureRecognizer:gestureRecognizer];
    
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
        [gestureRecognizer view].transform = CGAffineTransformRotate([[gestureRecognizer view] transform], [gestureRecognizer rotation]);
        [gestureRecognizer setRotation:0];
    }
}

// scale the piece by the current scale
// reset the gesture recognizer's rotation to 0 after applying so the next callback is a delta from the current scale
- (void)scalePiece:(UIPinchGestureRecognizer *)gestureRecognizer
{
    [self adjustAnchorPointForGestureRecognizer:gestureRecognizer];
    
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
        [gestureRecognizer view].transform = CGAffineTransformScale([[gestureRecognizer view] transform], [gestureRecognizer scale], [gestureRecognizer scale]);
        [gestureRecognizer setScale:1];
    }
}

- (void)adjustAnchorPointForGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        UIView *piece = gestureRecognizer.view;
        CGPoint locationInView = [gestureRecognizer locationInView:piece];
        CGPoint locationInSuperview = [gestureRecognizer locationInView:piece.superview];
        
        piece.layer.anchorPoint = CGPointMake(locationInView.x / piece.bounds.size.width, locationInView.y / piece.bounds.size.height);
        piece.center = locationInSuperview;
    }
}

Will provide you the link for the above sample code by Apple. I forget this now.



Wednesday, January 30, 2013

Take Bitmap from UIView

You can capture UIImage from any UIView by following function

*Note: Import the following class to use UIView layer properties 
 #import <QuartzCore/QuartzCore.h>

Code is :


+ (UIImage*)imageFromView:(UIView*)view
{
    [self beginImageContextWithSize:[view bounds].size];
    BOOL hidden = [view isHidden];
    [view setHidden:NO];
    [[view layer] renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    [self endImageContext];
    [view setHidden:hidden];
    return image;
}

+ (UIImage*)imageFromView:(UIView*)view scaledToSize:(CGSize)newSize
{
    UIImage *image = [self imageFromView:view];
    if ([view bounds].size.width != newSize.width ||
        [view bounds].size.height != newSize.height) {
        image = [self imageWithImage:image scaledToSize:newSize];
    }
    return image;
}

+ (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    [self beginImageContextWithSize:newSize];
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    [self endImageContext];
    return newImage;
}

Above Reference is taken from :

Drag and Drop UIImageView(s) inside UIView

i have put a UIView inside the xib and made the IBOutlet for this as property name - sampleView.

This UIView's x and y position is as per my project. So no need to worry about the parent view x and y position. Because we can make it relative to superview controller as follow:

//imagesView is Mutable Array and contains all UIImages.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
    
    for(int i=0;i<imagesInView.count;i++)
    {
        UIImageView *imgView = [imagesInView objectAtIndex:i];
        if (CGRectContainsPoint([imgView frame], [touch locationInView:self.secondFullImageView])) {
            //if ([touch tapCount] == 2)
                //[imgView setupNextDisplayString];
            CGPoint touchPoint = [touch locationInView:self.sampleView];//Here you need to concentrate for your UIImageView Parent
            [UIView beginAnimations:nil context:NULL];
            [UIView setAnimationDuration:0.3];
            imgView.center = touchPoint;
            CGAffineTransform transform = CGAffineTransformMakeScale(1.2, 1.2);
            imgView.transform = transform;
            [UIView commitAnimations];
            return;
        }
   }
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    for(int i=0;i<imagesInView.count;i++)
    {
        UIImageView *imgView = [imagesInView objectAtIndex:i];
        if (CGRectContainsPoint([imgView frame], [touch locationInView:self.sampleView])) {
            CGPoint location = [touch locationInView:self.sampleView];
            imgView.center = location;
        }
}
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    
    for(int i=0;i<imagesInView.count;i++)
    {
        UIImageView *imgView = [imagesInView objectAtIndex:i];
        if (CGRectContainsPoint([imgView frame], [touch locationInView:self.sampleView])) {
            //if ([touch tapCount] == 2)
            //[imgView setupNextDisplayString];
            [UIView beginAnimations:nil context:NULL];
            [UIView setAnimationDuration:0.3];
            CGAffineTransform transform = CGAffineTransformMakeScale(1, 1);
            imgView.transform = transform;
            [UIView commitAnimations];
            return;
        }
    }
}

This Code is not for Zoom, Pan or Rotate. For these features you can go here
http://varunxcode.blogspot.in/2013/01/simple-drag-drop-with-zoom-and-rotate.html

Random Number in xCode

Here is the code to generate the random number between some 2 values.



- (int) randomNumberFrom: (int) minValue to: (int) maxValue
{
    double probability = rand() / 2147483648.0;
    double range = maxValue - minValue + 1;
    return (int)(range * probability + minValue);
}

- (int) randomNumberFrom: (int) minValue to: (int) maxValue except:(int) exceptValue
{
    if(minValue == maxValue)
    {
        return minValue;
    }
    int result;
    while(exceptValue == (result = [self randomNumberFrom:minValue to:maxValue]))
    {
    }
    return result;
}


Reference taken from:

http://www.cocos2d-iphone.org/forum/topic/28378

Tuesday, January 29, 2013

load Web page in UIWebView


Following code is for iPad Portrait display. (wd: 640, ht: 960)

For landscape wd and ht can be swaped

    UIWebView *uview = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 640, 960)];
[self.view addSubview:uview];

[uview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"] cachePolicy:NSURLCacheStorageAllowed timeoutInterval:20.0]];

Monday, January 28, 2013

Work with UITabBarController dynamically


Here i have shown How to work with UITabBarController and How to add Items in It.
1. declare tabs in class ".h" file

    UITabBarController *tabs;

2. Then synthesize in ".m" file
@synthesize tabs;

3. Now Initiate this in viewLoaded and call createTabs

    tabs = [[UITabBarController alloc] init];
    [self createTabs];



- (void) createTabs
{
    UIViewController *viewController1 = [[FirstTabViewController alloc] initWithNibName:@"FirstTabViewController" bundle:nil];
    UIViewController *viewController2 = [[SecondTabViewController alloc] initWithNibName:@"SecondTabViewController" bundle:nil];
    UIViewController *viewController3 = [[ThirdTabViewController alloc] initWithNibName:@"ThirdTabViewController" bundle:nil];
    UIViewController *viewController4 = [[FourthTabViewController alloc] initWithNibName:@"FourthTabViewController" bundle:nil];
   
    tabs.viewControllers = [NSArray arrayWithObjects:viewController1, viewController2, viewController3, viewController4, nil];
    
    UITabBarItem *item1 = [[UITabBarItem alloc] initWithTitle:@"First" image:[UIImage imageNamed:@"1.png"] tag:1];
    UITabBarItem *item2 = [[UITabBarItem alloc] initWithTitle:@"Second" image:[UIImage imageNamed:@"2.png"] tag:2];
    UITabBarItem *item3 = [[UITabBarItem alloc] initWithTitle:@"Third" image:[UIImage imageNamed:@"3.png"] tag:3];
    UITabBarItem *item4 = [[UITabBarItem alloc] initWithTitle:@"Logout" image:[UIImage imageNamed:@"4.png"] tag:4];
    
    [viewController1 setTabBarItem:item1];
    [viewController2 setTabBarItem:item2];
    [viewController3 setTabBarItem:item3];
    [viewController4 setTabBarItem:item4];
    [self.view addSubview:tabs.view];
}

Sunday, January 27, 2013

Create UIView and work with UIImage

First Create UIView by following Coding



UIView *uview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 600, 600)];
[viewControl addSubview:uview];

Now to load the Image from External source is as follow:

   NSURL * imageURL = [NSURL URLWithString:@"http://ww.url.com/imageName.jpg"];
    NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
    UIImage * image = [UIImage imageWithData:imageData];
    UIImageView *block = [[UIImageView alloc] initWithImage:image];
    block.frame = CGRectMake(10, 10, 200, 200);
    [uview addSubview:block];
    block = nil;
    uview = nil;
    image = nil;
    imageData = nil;
    imageURL = nil;
    

I have used ARC - Automatic Reference counting. So didn't released the variable here.

Thursday, January 24, 2013

Login Shake effect in xCode

I have tested it and It works 


- (void)earthquake:(UIView*)itemView
{
    //AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); 

    CGFloat t = 5.0;

    CGAffineTransform leftQuake  = CGAffineTransformTranslate(CGAffineTransformIdentity, t, 0);
    CGAffineTransform rightQuake = CGAffineTransformTranslate(CGAffineTransformIdentity, -t, 0);

    itemView.transform = leftQuake;  // starting point

    [UIView beginAnimations:@"earthquake" context:itemView];//i used (__bridge void *)(itemView)
    [UIView setAnimationRepeatAutoreverses:YES]; // important
    [UIView setAnimationRepeatCount:3];
    [UIView setAnimationDuration:0.05];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(earthquakeEnded:finished:context:)];

    itemView.transform = rightQuake; // end here & auto-reverse

    [UIView commitAnimations];
}

- (void)earthquakeEnded:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context 
{
    if ([finished boolValue]) 
    {
        UIView* item = (UIView *)context;//I Used (__bridge UIView *)context
        item.transform = CGAffineTransformIdentity;
   }
}
Above code reference is taken from 

Wednesday, January 23, 2013

How to work with NSMutable Array and For Loop in xCode

first declare the Mutable Array in filename.h



#import <Foundation/Foundation.h>

@interface FileNameAsClassName: NSObject
{
    NSMutableArray *users;
}
@property(nonatomic,strong) NSMutableArray *users;
@end;

Now define this users array in filename.m


#import "FileNameAsClassName.h"

@implementation FileNameAsClassName
@synthesize users;

Now use this to add Objects in any function, where you required, after initialize

//Initializing
users = [[NSMutableArray alloc] init];

//Inserting Objects in some function, where required
[users addObject:someObjectName];


Now use this as below in required function 


for(int i=0;i<users.count;i++)
{
    someObjectName = [users objectAtIndex:i];
    //Now use someObjectName as Obejct, which you have inserted
}

Tuesday, January 22, 2013

How to Load External XML in xCode

1. Create a different class for this. Lets suppose XMLParse

Code for XMLParse.h is:



#import <Foundation/Foundation.h>

@interface XMLParse : NSObject <NSXMLParserDelegate>
{
    NSMutableString *currentElementValue;
    NSMutableArray *users;
}
@property(nonatomic, retain) NSMutableArray *users;

- (XMLParse *) initXMLParser;
- (void) loadDataFromXML;
- (void) doParse:(NSData *)data;
@end


Code for XMLParse.m is:


#import "XMLParse.h"
@implementation XMLParse
@synthesize users;

- (XMLParse *) initXMLParser
{
    users = [[NSMutableArray alloc] init];
    return self;
}

//XMLParsing
-(void) loadDataFromXML
{
    NSString *path=[[NSBundle mainBundle] pathForResource:@"UserInfo" ofType:@"xml"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    [self doParse:data];
}

- (void) doParse:(NSData *)data
{
    NSXMLParser *nsXMLParse = [[NSXMLParser alloc] initWithData:data];
    [nsXMLParse setDelegate:self];
    [nsXMLParse parse];
}

-(void) parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI
 qualifiedName:(NSString *)qName
    attributes:(NSDictionary *)attributeDict
{
    printf("User Info %s", [elementName UTF8String]);
    
    if([elementName isEqualToString:@"User"])
    {
        //Get the attribute value
        printf("XML - %s", [[attributeDict objectForKey:@"uname"] UTF8String]);
    }
}

-(void) parser:(NSXMLParser *)parser
 didEndElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI
 qualifiedName:(NSString *)qName
{
    printf("\nEnd ");
    if ([elementName isEqualToString:@"Users"]) {
        // We reached the end of the XML document
        return;
    }
    if ([elementName isEqualToString:@"user"]) {
        
    } else {
        
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if (!currentElementValue) {
        // init the ad hoc string with the value
        currentElementValue = [[NSMutableString alloc] initWithString:string];
    } else {
        // append value to the ad hoc string
        [currentElementValue appendString:string];
    }
    printf("Processing value for : %s", [string UTF8String]);
}
@end



How to call 


#import "XMLParse.h"

@interface ViewController ()
@property (nonatomic) XMLParse *parser;
@end
@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.parser = [[XMLParse alloc] initXMLParser];
    [self.parser loadDataFromXML];
}