Monthly Archives: January 2012

Control of the Week (Cocoa Controls)

Posted by Cocoa Controls at Cocoa Controls

We’ve all dealt with the hassle of constructing UITableViewController subclasses specifically to capture a couple pieces of data. Maybe you’ve even created a half-baked generic frameworky sort of thing to make the process easier. I know I have, at least twice. This isn’t any fun, and yet we keep doing it. I now know that there’s a better way to deal with these sorts of things, with this week’s Control of the Week: QuickDialog.

QuickDialog, from Eduardo Scoz, is a super-easy way to create HIG-compliant iOS forms for your apps without having to directly deal with UITableViews, delegates and data sources.

Check it out on YouTube

or grab a copy of the source code.

BSKeyboardControls (Cocoa Controls)

Posted by Cocoa Controls at Cocoa Controls
BSKeyboardControls makes it easy to put previous, next and done buttons above the keyboard in your iPhone or iPad app.

BSKeyboardControls is optimized for both iPhone and iPad and therefore fits perfectly in your universal app.

For usage instructions please follow the source code link.

image of this control

Cocos2D/Box2D Endless Platformer [Antoni Massó Mola] (iDevBlogADay)

Posted by Antoni Massó Mola at iDevBlogADay

It’s been a long time since my last iDevBlogADay contribution. I’ve been (and still am) very busy, but wanted to share with you this code. I’m working on an endless platformer game (www.sewerwars.com) and i didn’t find any tutorial or source code to help me start with the development so I’m sharing with the Cocos2D community part of my code.

I did find a tutorial from www.uchidacoonga.com (some of my code uses snippets from this tutorial) which helped me understand how to move Box2D objects.

With this demo you will be able to:

- Create endless platforms
- Build platforms with different sizes
- Position platforms in random positions
- Assign three CCSprite to the Box2D platform (see figure 1)

The code is optimized for iPhone retina, but with some minor modifications you can make it work under iPhone & iPad screens.

If you find any bugs or can optimize the code please let me know!

Click here to download the source code.

Cocos2D/Box2D Endless Platformer [Antoni Massó Mola] (iDevBlogADay)

Posted by Antoni Massó Mola at iDevBlogADay

It’s been a long time since my last iDevBlogADay contribution. I’ve been (and still am) very busy, but wanted to share with you this code. I’m working on an endless platformer game (www.sewerwars.com) and i didn’t find any tutorial or source code to help me start with the development so I’m sharing with the Cocos2D community part of my code.

I did find a tutorial from www.uchidacoonga.com (some of my code uses snippets from this tutorial) which helped me understand how to move Box2D objects.

With this demo you will be able to:

- Create endless platforms
- Build platforms with different sizes
- Position platforms in random positions
- Assign three CCSprite to the Box2D platform (see figure 1)

The code is optimized for iPhone retina, but with some minor modifications you can make it work under iPhone & iPad screens.

If you find any bugs or can optimize the code please let me know!

Click here to download the source code.

JWFolders (Cocoa Controls)

JWFolders is a set of classes that attempt to mimic the folder animation present on the iOS SpringBoard.

image of this control

SOURCE LINK from Cocoa Controls

Using Cocos2D in a UIKit project [Ben Williams] (iDevBlogADay)

I recently needed to add a “water ripple” effect to a project. Although there is a simple water ripple effect built-in to the SDK, it really didn’t fill my needs. It seemed like my only options would be to quickly boost my OpenGL skills (from none to something), or find an alternative. I soon found a really nice water ripple effect built for Cocos2D, which was exactly what I wanted. The only stumbling block was how to integrate Cocos2D into my existing UIKit project. As it turns out, it’s fairly simple.

First, download the source for Cocos2D. If your UIKit project is using ARC, you’ll need to download the “bleeding edge” version from GitHub, as this is currently the only version in which the header files are all ARC friendly. If you are not using ARC, the latest stable version should be fine (currently v1.0.1). Once you have the Cocos2D source, locate the file “cocos2d-ios.xcodeproj”. Open up your UIKit project, and drag this file into your file navigator. You should end up with something like this:

Next, go to the Build Phases settings for your project, and add the Cocos2D library (libcocos2d.a) as a linked library. You’ll probably also need to add OpenGLES.framework, and libz.dylib, like so:

You’ll also need to modify your Build Settings. Set Always Search User Paths to YES, and add the Cocos2D source directory to the User Header Search Paths (as a recursive path):

At this point, you should be able to import the “cocos2d.h” header into one of your source files, and compile your project. If you are using ARC and get some build errors, make sure your Cocos2D source is the development (bleeding edge) branch. Even though Cocos2D itself is not ARC enabled, it’s no problem to combine it with an ARC enabled project, provided you are using the correct version.

Now that Cocos2D is part of your project, it’s time to write some code. I only needed Cocos2D in one small part of my application, so I decided to limit it to a single UIViewController. This is the code that I used:

 - (void)viewDidLoad { 	[super viewDidLoad];  	CCScene *introScene = [CCScene node]; 	self.introLayer = [IntroLayer node]; 	[introScene addChild:self.introLayer];  	if(![CCDirector setDirectorType:kCCDirectorTypeDisplayLink]) { 		[CCDirector setDirectorType:kCCDirectorTypeDefault]; 	}  	CCDirector *director = [CCDirector sharedDirector]; 	EAGLView *glView = [EAGLView viewWithFrame:CGRectMake(0, 0, 1024, 768) 			pixelFormat:kEAGLColorFormatRGB565 depthFormat:0]; 	[director setOpenGLView:glView]; 	[director setDeviceOrientation:kCCDeviceOrientationPortrait]; 	[director setAnimationInterval:1.0/60]; 	[self setView:glView]; 	[CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGB565]; 	[[CCDirector sharedDirector] runWithScene:introScene];  	[self.introLayer setupScene]; }  - (void)runRippleAnimation { 	[self.introLayer runRippleAnimation]; }  - (void)endRippleAnimation { 	CCDirector* director = [CCDirector sharedDirector]; 	[director end]; } 

I won’t go through the details of how to create a CCScene and CCLayer – there’s plenty of Cocos2D tutorials out there. The code that you’ll be most interested in is this:

 if(![CCDirector setDirectorType:kCCDirectorTypeDisplayLink]) { 	[CCDirector setDirectorType:kCCDirectorTypeDefault]; }  CCDirector *director = [CCDirector sharedDirector]; EAGLView *glView = [EAGLView viewWithFrame:CGRectMake(0, 0, 1024, 768) 			pixelFormat:kEAGLColorFormatRGB565 depthFormat:0]; [director setOpenGLView:glView]; [director setDeviceOrientation:kCCDeviceOrientationPortrait]; [director setAnimationInterval:1.0/60]; [self setView:glView]; [CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGB565]; [[CCDirector sharedDirector] runWithScene:introScene]; 

This basically sets up the Cocos2D environment, and starts running your CCScene. And that’s it! I presented this UIViewController modally, but I expect you should be able to use this method within a subview just as easily.

Combining UIKit and Cocos2D does suffer a performance hit, but I’m not doing anything overly complex here, so it wasn’t a problem. I’m also not sure if this is entirely the correct way to do things, but again – it works, so I’m happy.

Cocos2D has a heap of really nice effects, with a great community behind it. If you need some extra pizazz in your app, it might just be the way to go.

SOURCE LINK from iDevBlogADay

F3Swirly (Cocoa Controls)

I needed a control which had visual aspects of both an activity
indicator as well as an annunciator. This control satisfies that
need by providing, textual, color, and animated feedback.

The control uses Quartz 2D and Core Animation to provide a reasonable
level of performance with virtually no CPU overhead required for the
animation. The number of segments, segment color, segment thickness,
rotation rate, and text can all be customized.

I hope you find this useful!

image of this control

SOURCE LINK from Cocoa Controls

UIStoryboard Power Drill [Jason Lust] (iDevBlogADay)


I’ve read some good reasons why Storyboards are not ready for prime time. Some of the articles like Jonathan at toxic software.com simply help me find out that I wasn’t doing something wrong, it just wasn’t meant for that. But there are some benefits from using a storyboard that I wanted to keep, so I got adamant about finding workarounds. Here’s one:

Drill down UITableViews – Standard

1. Provided you’ve started with a subclassed UITableViewController, or a TableView in a UIViewController that is already the root relationship from a UINavigationController.

2. You link the push outlet from the cell prototype back to the table view controller.
This will automatically provide the control to push-in another of the same ViewController when a cell is clicked.

3. Give the loopback segue an identifier string in the attributes inspector.

4. Instead of implementing tableView:didSelectRowAtIndexPath: in the subclassed viewcontroller you will use
prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

This method will be passed the segue object that is the “tableLoopBack” the sender object for this segue type will be the UITableViewCell.

5. Prepare what data to send to the next instance the the table.

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
    NSArray* myObjectArray;
    UITableView* myTable;
    
    if ([segue.identifier isEqualToString:@"tableLoopBack"]) {
        SubClassedTable* nextSct = segue.destinationViewController;
        UITableViewCell* myCell = (UITableViewCell*)sender;
        NSIndexPath* idx = [myTable indexPathForCell:myCell];
        nextSct.myObject = [self.myObjectArray objectAtIndex:idx.row];
    }
}

6. In the TableDataSourceDelegate have it decide how to propagate your tables data array based now on the defined and set value of “myObject”. This is very different for everyones data types.

An example, using Core Data and have say AMusicLib > Artists > Albums > Songs > Info

The myObject would ideally be of type NSManagedObject* so that you could be any of the above. When the dataDelegates are called like tableview:numberOfRowsInSection: you would want to implement something like the following to handle the many layers.

- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([self.myObject isKindOfClass:[Music class]]) {
        Music* myMusicLib = self.myObject;
        return [myMusicLib.artists count];
    } else if ([self.myObject isKindOfClass:[Artist class]]) {
        Artist* myArtist = self.myObject;
        return [myArtist.albums count];
    } else if ([self.myObject isKindOfClass:[Album class]]) {
        Album* myAlbum = self.myObject;
        return [myAlbum.songs count];
    }
}

Now in the implementation of the tableview:cellForRowAtIndexPath: use a similar kindOf conditional so that the cells properties can feed from the difference of the objects at each layer.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @”musicCell”;
    UITableViewCell* newCell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if ([self.myObject isKindOfClass:[Music class]]) {
        Music* myMusicLib = self.myObject;
        Artist* aArtist = [[myMusicLib.artists allObjects] objectAtIndex:indexPath.row];
        newCell.textLabel.text = aArtist.name;
    } else if ([self.myObject isKindOfClass:[Artist class]]) {
        Artist* myArtist = self.myObject;
        Album* aAlbum = [[myArtist.albums allObjects] objectAtIndex:indexPath.row];
        newCell.textLabel.text = aAlbum.title;
        newCell.imageView.image = [UIImage imageNamed:aAlbum.art];
    } else if ([self.myObject isKindOfClass:[Album class]]) {
        Album* myAlbum = self.myObject;
        Song* aSong = [[myAlbum.songs allObjects] objectAtIndex:indexPath.row];
        newCell.textLabel.text = aSong.name;
        NSDate* aTime = [NSDate dateWithTimeIntervalSince1970:[aSong.length intValue]];
        NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        [dateFormatter setDateFormat:@"m:ss"];
        newCell.detailTextLabel.text = [dateFormatter stringFromDate:aTime];
    }
    return newCell;
}

And finally because earlier we used a property self.myObjectArray, this property could have been a consistent type simple array, but because I walked you through handing down different managedObjects this myObjectArray getter would also need to return an NSArray from the different managedObject’s intended NSSet. Same as just above, just return [myArtist.albums allObjects] or [myAlbum.songs allSongs] and so on for the prepareForSegue can hand off the right object to the next controller.

Drill Down TableViews – Options

The above is simple but can be limiting. The segue always pushes down to another of the same table view. Now you want options, lets go this why, or that.

1. Don’t use the push outlet on the cell prototype. This is whats limiting the control of where we go.

2. Do Implement the tableView:didSelectRowAtIndexPath: this is where we will decide what segue we take, Or none.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (!sec) {
        Section* aSect = [[self.sectionFetchedController fetchedObjects] objectAtIndex:indexPath.row];
        [self performSegueWithIdentifier:@"tableLoopBack" sender:aSect];
    } else {
        Clip* aClip = [self.clipFetchedController objectAtIndexPath:indexPath];
        [[VideoPlayerController Player] setMoviePlayerForClip:aClip];
    }
}

What we are effectively doing here is getting the option to loop into another table, or stay and do something else like load a video in a modal MPMoviePlayerController. Or even call another segue that goes to detail view.

3. Continue to make use of the prepareForSegue method

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"tableLoopBack"]) {
        VideoListController* vlc = segue.destinationViewController;
        Section* mySec = (Section*)sender;
        vlc.title = mySec.title;
        vlc.sec = mySec;
    }
}

This is so data is still passed to the new instance of this controller for drill down purposes, even if not all cells drill.

4. And now the hack, if in step 1 we do not link the cell to push to the this viewController, we still need to define a segue and name it “tableLoopBack”.
Add a UIBarButtonItem to the viewController and set the push outlet on it to loopback, identify that new segue connection as “tableLoopBack” and you have access to it when calling performSegue.

5. Add another UIBarButtonItem, and link it to another ViewController like one that layout details level. Identify that segue as another name like “detailSegue” and performSegue from didSelectRowAtIndexPath: where you can pass down the object full of details right into the sender, which will also be handed through the prepareForSegue, so make sure you hand it down again to the desired property of the new destinationViewController.

Helpful? Vote me up: Stackoverflow.com

SOURCE LINK from iDevBlogADay

Unit testing for blocks based APIs [Marin Todorov] (iDevBlogADay)

Unit tests are very useful for those large projects where you might loose sight of everything that’s going on and while you are adding new code to add feature X you might be silently breaking feature Y without even suspecting. It’s super easy these days to add unit tests to your Xcode project – when you create new Xcode project just check the checkbox in the save dialogue and voila everything is setup automatically for you:

This will add unit testing to your project and when you click Product->Test from Xcode’s menu your unit test will be run. Cool and smooth.

Let’s have a look at the default unit test, which is created for you- you get a folder called “[Project name]Tests” and inside there’s one test pre-set for you. Open the .m file and find the only test inside:

- (void)testExample {     STFail(@"Unit tests are not implemented yet in utb_testTests"); }

It’s designed so that it’ll fail by default. Eventually if you run the tests (Cmd+U) you’ll see the tests fail (though my experience shows even this simple example test will succeed for no reason many times):

So in this article I’m not going to explain how unit tests work and so on, but I’d rather cover how to overcome some obstacles if you are writing unit tests for block based APIs.

Unlike your iPhone apps the unit test suite is being started, it runs the code of all tests and then when there’s nothing more to run it just exists. If it didn’t spit any exception, the test was successful. End of story.

So let’s see how that pairs up with using blocks. Let’s replace the content of the test method with this code:

- (void)testExample {     CLGeocoder* gc = [[CLGeocoder alloc] init];     [gc geocodeAddressString:@"Hermannplatz, Berlin, Germany"      completionHandler:^(NSArray *placemarks, NSError *error) {            STFail(@"Failed inside a block");        }]; }

This code creates a new geocoder and asks for matches for the given address. Since the API is asynchronous the results are fetched inside the provided block. You’ll need to also add an import at the top of the file:

#import <CoreLocation/CoreLocation.h>

and of course add the CoreLocation.framework to the project.

Hit Cmd+U and … the test passes. Inevitably and always.

So why does this happen?

The test suit doesn’t wait for and don’t know that you are waiting for geocoding results from Apple’s server. It runs all the code and then when there’s no more code to run – exits.

Problem?

You actually need to make the application hang around alive until you get the results for the geocoding server and only tell it “i finished my work you can exit now please”. But naturally if you just tell the app to sleep it won’t be able to react when the results come back from the server …

Some diggin’ through StackOverflow finds me this solution which I really like:

stackoverflow.com/a/4326754/208205

dispatch_semaphore_t sema = dispatch_semaphore_create(0);   [object runSomeLongOperationAndDo:^{     STAssert…       dispatch_semaphore_signal(sema); }];   dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER); dispatch_release(sema);

Using Grand Central Dispatch and its C functions you can create a semaphore object and wait till the signal comes in. However there are 2 things I don’t like in this code:

  1. using C functions and
  2. I have rather complex class structure of classes, so passing reference to the semaphore is rather inconvenient.

So I quickly came up with a simple class to implement my own semaphore. It has two handy methods – waitForKey:(NSString*)key and lift:(NSString*)key … and here’s how you use it:

- (void)testExample {     CLGeocoder* gc = [[CLGeocoder alloc] init];     [gc geocodeAddressString:@"Hermannplatz, Berlin, Germany"      completionHandler:^(NSArray *placemarks, NSError *error) {            STFail(@"Failed inside a block");          [[TestSemaphore sharedInstance] lift:@”geocode1”];      }];   	[[TestSemaphore sharedInstance] waitForKey:@”geocode1”]; }

Pretty straight forward – and since it’s a singleton class you can call it from wherever you want. Also it is free and available for download if you want to tingle with unit testing. And hey – it’s a semaphore, so you can use it for whatever purpose suits you :)

Sempahore code download

Marin

SOURCE LINK from iDevBlogADay

A pullable view implementation (like Notification Center) [Fábio Rodella] (iDevBlogADay)

For an app I’m designing at the moment I had the need to use a pullable view (sliding drawer) similar to how the iOS 5 Notification Center works, where you can flick or drag a handle to reveal or hide additional content. After looking for an existing open-source implementation of such feature and finding squat, I decided to create my own and share it with the interwebs.

The PullableView class tries to mimic the behaviour of the Notification Center view as closely as possible, and is very flexible. You can define and style your handle area, and the view can be pulled from any direction in the X or Y axes. To define the “open” and “closed” states you simply set the center point for the view at these states; if both points have the same X coordinate the sliding will happen in the vertical axis, or the horizontal axis if the Y coordinates are equal. You can also set a flag indicating if the view state should be toggled by simply tapping the handle area.

The sample project includes a view controller which uses 3 pullable views demonstrating many usage scenarios, but if you have additional questions or want to report a bug add a comment to this post.

You can download the source code from our Github repo. I’ve also added this component to the Cocoa Controls website. Hope you find it useful!

SOURCE LINK from iDevBlogADay

WP Like Button Plugin by Free WordPress Templates