iphone adjustable UITextField when keyboard popup

In iphone programming there is no direct method to move the UITextField above the keyboard. Instead we do some adjustment.

Iphone keyboard occupies the bottom 216 pixels on the screen so the UITextField placed at the bottom will not be visible. Try this method

The first function will move the UITextField to the position we specify.Here i want to move it to 100(y coordinate)

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    textView.center = CGPointMake(textView.center.x, 100);
    [UIView commitAnimations];
}

When the TextView editing is completed,it will move to the original position(274)

- (void)textViewDidEndEditing:(UITextView *)textView
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    textView.center = CGPointMake(textView.center.x, 274);
    [UIView commitAnimations];
}

The important point is
You will need to make the view controller the delegate (in Interface Builder) for every UITextField you want to animate.


How to Fix ‘Warning : Multiple Build Commands For Output File' ?

Hi,

The following warning, ‘Multiple Build Commands For Output File’ occurs when you try to delete resource files by ‘delete reference’ other than the correct method of‘move to trash’ while deleting files from ‘Resources’ folder of your project. Therefore the Copy Bundle Resources still holds the references of the same file you have deleted and it shows the multiple build commands for the output file after you added the same files over again.

How to Fix? :

Go to the Targets->YourProject->Copy Bundle Resources

From ‘Copy Bundle Resources’ delete those files whose reference are still there or files which shows the warning.

Here ‘YourProject’ is your project name.
:)

How to get NSPopUpButton Selected Item Name ?

Hi,

In order to get the selected item name from an NSPopUpButton using in any iOS application, use the following sample of code.

NSPopUpButtonCell *urCell = [sender selectedCell];
NSLog (@"Item name in the cell is %@", urCell.title);

:)

How to remove duplicates from NSMutableArray ?

Hi,

For removing or deleting duplicates from a NSMutableArray , use the following lines of code. It will simply check for duplicates elements and get it deleted or removed.


NSArray *tempArr= [urArray copy];

NSInteger idx = [tempArr count] - 1;

for (id object in [tempArr reverseObjectEnumerator]) {

     if ([urArray indexOfObject:object inRange:NSMakeRange(0, index)] !=NSNotFound) {

           [urArray removeObjectAtIndex:idx];
     }

idx--;

}
[tempArr release];

:)

How to set iPhone/iPad table view transparent ?

Hi,

In order to simply set the iPhone/iPad table view transparent use the following line of code.

urTblView.backgroundColor = [UIColor clearColor];

Here ‘urTblView’ is the table view that you want to make transparent. Try it out. This single line will make your table view transparent and looks better.
:)

How to change z order value of a sprite in Cocos2D ?

Hi,

Sometimes during the execution of program you may need to change the z order value of sprite for better working. Use the following sample of code to change the z order value of a sprite in Cocos2D/Box2D iPhone programming.

CCSprite *urSprite = [CCSprite spriteWithFile:@"coderzheavenLogo.png"];
urSprite.position = ccp(240,160);
//First setting the z value to 1
[self addChild:urSprite z:1];
.
.
.
.
.
//After some other executions are over setting z value to 7
[self reorderChild:urSprite z:7];

:)

How to get a Sprite by tag in Cocos2D ?

Hi,

Sometimes you may need to get a sprite using tag while doing a project using Cocos2D. It’s easy to get a sprite by a tag in Cocos2D, use the following code to get it.

tempSprite = (CCSprite*)[self getChildByTag:7];

Here ‘tempSprite’ is your CCSprite and it will get the sprite with tag 7.
:)

How to make a sprite visible and invisible in Cocos2D ?

Hi,

In order to make a sprite completely invisible , use the following code while using Cocos2D, this code will set the visibility of your sprite to zero.

urSprite.visible = 0; 

In order to make a sprite completely visible, use the following code while using Cocos2D, this code will set the visibility of the sprite back to one.

urSprite.visible = 1; 

:)

Mute and Unmute Sound in Cocos2D

Hi,

In order to mute and unmute sound in Cocos2D iPhone, use the following code.

if ([[SimpleAudioEngine sharedEngine] mute]) {
            // This will unmute the sound
            [[SimpleAudioEngine sharedEngine] setMute:0];
}
else {
             //This will mute the sound
             [[SimpleAudioEngine sharedEngine] setMute:1];
}

:)

How to programmatically set UITextView font and size

Hi,

In order to set font and size of a UITextView programmatically use the following code.

self.urTxtView.font = [UIFont fontWithName:@"Zapfino" size:customSize];

:)

iPhone NSData to NSString Conversion

Hi,

Use the following line of code to convert NSData to NSString in iPhone/iPad using Objective C.

NSString *convertedString =[ [NSString alloc]initWithData:yourData];

Here ‘yourData’ is your NSData which you want to convert to NSString. :)

How to detect single/double/triple taps in iPhone ?

Hi,
How can you detect single/double/triple taps in iPhone using Objective C?
Use the following code to detect single or multiple taps in iPhone/iPad/iPod.
The code can also be used with Cocos2D & Box2D.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *urtouch = [touches anyObject];

    NSUInteger urtapCount = [urtouch tapCount];

    switch (urtapCount) {

       case 1:
         NSLog(@"Single Tap Detected!");
          break;

       case 2:
          NSLog(@"Double Tap Detected!");
          break;

       case 3:
        NSLog(@"Triple Tap Detected!");
        break;

      default :
       break;

   }
}

Try it out! You can even detect Quadrup! :)

Cocos2D CCMenu – An Example

Hi,

While using cocos2D you may need to create some scenes with menu items on it. This example given below shows , how to create a cocos2D menu scene with menu items using images. You can have your own custom fancy image text indicating menu items using this.


//Creating the three menu items.
//You can use different images for selected view & normal view.
//On clicking menu will show selectedImage
CCMenuItemImage *Item1 = [CCMenuItemImage
                        itemFromNormalImage:@"Walk.png"
                        selectedImage:@"WalkTwo.png"
                        target:self
                        selector:@selector(walkAction:)];

CCMenuItemImage *Item2 = [CCMenuItemImage
			           itemFromNormalImage:@"Run.png"
				       selectedImage:@"RunTwo.png"
				       target:self
				       selector:@selector(runAction:)];

CCMenuItemImage *Item3 = [CCMenuItemImage
				       itemFromNormalImage:@"Jump.png"
				       selectedImage:@"JumpTwo.png"
				       target:self
				       selector:@selector(jumpAction:)];

//Adding menu items to the CCMenu. Don't forget to include 'nil'
CCMenu *selectMenu= [CCMenu menuWithItems:Item1, Item2, Item3, nil];
//Aligning & Adding CCMenu child to the scene
[selectMenu alignItemsVertically];
[self addChild:selectMenu];


//Different functions on below get called according to the menu item clicked.
- (void)walkAction:(id)sender
{
    [[CCDirector sharedDirector] replaceScene:[WalkingScene node]];
}

- (void)runAction:(id)sender
{
   [[Director sharedDirector] replaceScene:[runningScene node]];
}

- (void)jumpAction:(id)sender
{
    [[Director sharedDirector] replaceScene:[jumpingScene node]];
}

:)

Identifying sprite associated with a particular body in Box2D

Hi,

How can you identify the sprite associated with a particular body while using box2D ? Sometimes you may need to identify the sprite associated with the body you are using. For that use the following line of code.

CCSprite *yourSprite= (CCSprite*)yourBody->GetUserData();

Now you got the corresponding sprite in your ‘yourSprite’
:)

How to find distance between two CGPoint in Cocos2D ?

Hi,
Sometimes you may need to find the distance between two CGPoint in cocos2D or box2D using Objective C. See the following code to see how you could do that.

CGPoint first= CGPointMake(50,50);
CGPoint second= CGPointMake(200,200);
float maxDistance= ccpDistance(first, second);

:)

How to detect shake in iPhone ? An example

Hi,
Sometimes you may want to detect shake gesture in iPhone using your programs. But how can you detect shake gesture in iPhone? Shake gesture in iPhone can be detected by using the accelerometer. The following lines of code can be used for detecting the shake gesture in iPhone. You can use these lines of code in your cocos2D applications/games.

First of all you MUST enable accelerometer in the init function

isAccelerometerEnabled = YES;

Then use the following function to detect the shake gesture.

- (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration
{
    if(abs(acceleration.x-oldX )>0.7 || abs(acceleration.y-oldY)>0.7)
   {
       NSLog(@”Yupie! Shake detected!”);
   }
oldX = acceleration.x;
oldY = acceleration.y;
}

Here oldX & oldY are variables that store accelerometer values and 0.7 is the value you are giving to check for shake gesture. That’s it. :)

How to remove box2D body from world ?

Hi,
If you are a game developer and you are using box2D for real world simulations, you would probably need a particular body to be removed from the box2D world! But how can you remove box2D body from world ? See the following sample code which does the same.

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{

//Getting Touch Locations
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL: location];

//Converting to cocos2D positioning
b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);

     //Getting body list from world
     for (b2Body* b = world->GetBodyList(); b; b = b->GetNext()) {
          //Getting Fixture from the bodies
          b2Fixture *bf1 = b->GetFixtureList();
          //Checking whether the fixture contains touch location!
          if (bf1->TestPoint(locationWorld)) {
             //If YES assigning user data to a sprite tempSprite
             CCSprite *tempSprite = (CCSprite *) b->GetUserData();
             //Checking whether the user data sprite tag is 7
             if (tempSprite .tag==7) {
                //If YES then remove the sprite & the body!
                [self removeChild:tempSprite cleanup:YES];
                world->DestroyBody(b);
             }
        }
    }
}

Here tag 7 is what we previously assigned for the sprite corresponding to the body’s user data!

How to find whether an item is in NSArray or not ?

Hi,

Sometimes you may need to find/search a particular item in NSArray. How can you find whether a particular item is present in NSArray or not? Look at the code below.

BOOL testFlag= [yourArray containsObject:@"CoderzHeaven"];
if(testFlag) {
	NSLog(@“Yup! It's present!"); }
else {
	NSLog(@"Nopes! It's absent!"); }

Here ‘yourArray is your NSArray and ‘containsObject’ returns either TRUE or FALSE and it get stored in ‘testFlag’.
:)

How to empty an NSMutableArray ?

Hi,

Sometimes you may need to empty an NSMutableArray which is already initialized with some objects. You don’t need to release it and again alloc it for future use! You can simply empty an NSMutableArray using the following line of code.

[yourArray removeAllObjects];

Here ‘yourArray’ is your NSMutableArray. :)

Cocos2D Sprite Sheet Animation

Hi,

Suppose you have a sprite sheet of the desired animation you want. But how will you use that sprite sheet animation in your program using cocos2D? That’s simple. See the following code first.

Note : But how to make a sprite sheet? That topic can be found here. Making of sprite sheets from individual images are well discussed in that post.


//Initializing a CCSpriteBatchNode with our sprite sheet image
CCSpriteBatchNode *newSpriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"jumpingOver.png"];

//Adding the spriteSheet to the layer & setting the z orientations
[self addChild:spriteSheet z:14];

//Creating Frames from the frames file jumpingOver.plist
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"jumpingOver.plist"];

//Initializing a sprite with the first frame from plist
CCSprite *jumper = [CCSprite spriteWithSpriteFrameName:@"jump1.png"];

//Creating an NSMutableArray for adding the frames from plist
NSMutableArray *framesArray = [[NSMutableArray array] retain];

//Iterating for the total number of frames from plist
//Here supposing our jumpingOver plist have 15 images
for(int i=0; i<15; i++){
//Adding frames to our framesArray from the frames
[framesArray addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"jump%d.png",i]]];
}

//Creating an animation using the frames in framesArray
CCAnimation *jumping = [CCAnimation animationWithFrames:framesArray delay:0.25f];

//Setting our jumper sprite sprite sheet animation to the position of one another sprite
//oldSprite is our previous sprite on that position we are adding the animation
jumper.position=oldSprite.position;

//Creating action from the animation jumping
CCAction *jumpAction= [CCAnimate actionWithAnimation:jumping];

//running the action on jumper sprite with the sprite sheet animation action on jumpAction
[jumper runAction:jumpAction];

//Adding the jumper sprite to the layer with z orientation
[self addChild:jumper z:15];

If you have any doubt in animating your sprite sheets or about creating a sprite sheet , please feel free to comment us!

Email id verification using Objective C

Hi,

In order to verify an email address you have entered is valid or not using Objective C, use the following code.

- (BOOL) checkYourMail: (NSString *) myEmail{
      NSString *checkMail= @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4}";
      NSPredicate *matchMail = [NSPredicate predicateWithFormat:@"Matching %@", checkMail];
      return [matchMail evaluateWithObject:myEmail];
}

:)

Pausing & Resuming Sound in Cocoa Mac

Hi,

If you want to Pause an instance of NSSound which is being played in Cocoa Mac, use the following line of code.

[yourSound pause];

‘yourSound’ is the NSSound Object.

Similarlyl for resuming NSSound in cocoa Mac

[yourSound resume];

How to make a sprite visible and invisible in Cocos2D ?

Hi,
In certain situations you may need to make visible or invisible certain sprites. But how to set a sprite visible and invisible in Cocos2D? See the following Cocos2D code.

//Set the sprite's visible value to 1 to make it visible
yourSprite.visible = 1;
//Set the sprite's visible value to 0 to make it invisible
yourSprite.visible = 0;

:)

How to change the Z value of a Sprite during an action in Cocos2D ?

Hi,
There may arise some situations where you need to change the z value of a particular sprite during an action in Cocos2D. So how can you do that? See the following lines of code.

CCSprite *sample= [CCSprite spriteWithFile:@"trialImage.png"];
sample.position = ccp(160,240);
[self addChild:sample z:1];
/* Some of your actions goes here! */
[self reorderChild:sample z:9];

This will re order the sprite’s tag to 9 from 1 after ‘your actions’. :)

How to create an action when a UITextField is clicked ?

Hi,
Want to invoke an action when a text field (UITextField) is clicked using Objective C? Use the following.

[myTextField addTarget:self action:@selector(textFieldTouched:) forControlEvents:UIControlEventTouchDown];
- (void) textFieldTouched:(id)sender {
        //Here goes your actions on TextField Clicked
}

:)