Posted by Cocoa Controls at Cocoa Controls
This project aims to replicate UITabBarController functionality and behavior, but with a vertical tab bar.

Posted by Cocoa Controls at Cocoa Controls
This project aims to replicate UITabBarController functionality and behavior, but with a vertical tab bar.

Posted by Ryan Dillon at iDevBlogADay
Creating a responsive user interface is one of the most important considerations for a mobile developer, and the smooth scrolling and quick responsiveness of iOS has been one of its hallmarks since day 1. — I’ve gotta be honest here; I still find myself every now and then finding great amusement in just flicking around a simple web view or scrolling some text on my phone. It just feels so right! — Keeping a smooth flow and one to one correspondence between user touch and visual display is crucial for maintaining the illusion and feeling that one is directly interacting with the objects on the screen. One key consideration to make this happen is do not block the main thread. If you are doing anything that might take a significant amount of time, you must do this on a background thread.
With iOS 4.0 and the introduction of blocks and Grand Central Dispatch, it became much easier to complete tasks in the background asynchronously without having to dive into the implementation details of threads and such. If you haven’t yet tried out GCD, take a look at the docs, or check out this tutorial to get you up and running quickly. It’s great for parsing data, downloading from the network, etc. off the main thread, and GCD makes it very easy to write code that will call back into the main thread once the background process completes. What it doesn’t work well for is anything to do with UIKit or the user interface. All drawing and touch interaction takes place, by design, on the main thread. So, what do you do if your drawing itself is taking too long and blocking the main thread? I’m sure there were people much cleverer than me who found some ways to get around it and do some drawing in the background, but basically up until iOS 4, UIKit was not thread-safe at all. If your drawing is too complicated and blocks, then you need to optimize it or simplify it. However, the release notes for iOS 4.0 contain the following short section:
Drawing to a graphics context in UIKit is now thread-safe. Specifically:
- The routines used to access and manipulate the graphics context can now correctly handle contexts residing on different threads.
- String and image drawing is now thread-safe.
- Using color and font objects in multiple threads is now safe to do.
This was not something I had really been interested in or concerned myself with until I ran into just such a problem recently. I created a custom subclass of UILabel which adds a colored, blurred shadow to the label to give it a glow effect. But, this drawing took drastically longer than the regular string drawing. For example, for the drawing that happens at app startup, using regular UILabels takes 104 milliseconds total in drawRect:. To draw the exact same strings with shadows takes 1297 milliseconds! So, you can imagine what this does to frame rates when there are multiple labels being updated rapidly during an already CPU intensive section of the code.
Since I already know ahead of time exactly what strings I need to display during this particular bottleneck, it would be nice to be able to draw all the labels at once in the background and cache them for later. My first approach was, a bit naïve. Well, I thought, that paragraph in the iOS 4 release notes says something about graphics contexts and string drawing being thread-safe, and with GCD I can easily create a bunch of labels in the background and then send them back to the main thread. The creation part worked out just fine, but because of the way the graphics run loop works, the drawing didn’t happen until it was time for them to appear onscreen. So, no advantages there. How about if I create my own graphics context and call drawRect: myself while in the background thread? Generally, you want to let the system call this because it’s very intelligent about knowing when views need updated and how to synchronize that with the animation frame rate and display refresh cycle. But what if you actually want to call it? That turned out to be no good either. The labels would draw in the background, but then would just redraw back on the main thread. Again, no performance improvement, probably a loss actually. After a trip to the developer forums and a quick helpful response to my question, I realized I was going about this completely the wrong way. And of course, after reading those release notes a bit more clearly, I saw what my problem was: drawing to a graphics context is thread-safe, and string and image drawing are thread-safe, but this doesn’t mean the standard UIKit objects play nicely with multiple threads. As my experiments showed, the main run loop does what it does, and even if something like a UILabel is already created and forced to draw before it is presented on the screen, as soon as it appears onscreen for the first time, it gets the signal to redraw. Part of the reason I pushed things as far as I did is because there’s so much convenience to UILabel drawing that you don’t get as easily when you’re dealing with CoreGraphics text rendering directly, but just as I suspected earlier and ignored: CoreGraphics/Quartz is the way to go. So, here’s what I finally figured out. So far it seems to be working:
On a background thread – dispatched to a background queue with GCD – do the following:
UIFont *labelFont = [UIFont fontWithName:@"Helvetica" size:32.0];
NSString *labelText = @”Foo”;
CGSize viewSize = [labelText sizeWithFont:labelFont];
UIGraphicsBeginImageContextWithOptions(CGSizeMake(viewSize.width, viewSize.height), NO, 0.0);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, textColor.CGColor);
CGContextSetShadowWithColor(context, CGSizeZero, shadowRadius, shadowColor.CGColor);
[labelText drawInRect:CGRectMake(0.0, 0.0, viewSize.width, viewSize.height) withFont:labelFont lineBreakMode:UILineBreakModeClip alignment:UITextAlignmentCenter];
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
[imageArray addObject:theImage];
UIGraphicsEndImageContext();
By creating the string first, we can then get the size of the rectangle we’ll need to fit the string at a given font and size. Then create a new graphics context to draw into, at the needed size. The BOOL parameter is to mark the context as opaque. The final parameter is a scale, and by inserting “0.0? we tell the context to just render at the scale of the current screen. That way, we automatically maintain resolution independence for retina and non-retina devices. Then, after setting the colors and shadow, we draw the string into the context. Next, the key step: create a UIImage object from the current graphics state. Finally, make sure to end the context. Once all that is complete, you now have a UIImage object which can be passed back to the main thread and displayed in a UIImageView or used as the contents for a CALayer. One reason I decided to write this little tutorial is that most of what I found in my own googling and on the dev forums for info on background thread drawing was actually stuff written before iOS 4.0. So basically it said don’t do it! My example here obviously covers one particular case, but hopefully the pattern is clear. The main take away for me was to be reminded that UIKit as a whole is still not thread-safe, including the methods such as drawRect:. The drawing which is thread-safe is the specific creation of a graphics context and the Quartz calls used to draw into and manipulate that context. To get what you’ve drawn to the screen, you must pass it back to the main thread as an image and then use it from there however you want.
I noticed pretty early on that my frame rate was suffering during a certain user interaction, but it took me a while to realize that the label drawing was actually the problem. As I’ve already said, there was quite a lot of other extra code that needed to run during this same process, so I figured the whole thing was just a bottleneck in general. But, as soon as I fired up Instruments and saw the ridiculous amounts of time being spent in [UILabel drawTextInRect:], I knew I had to do something different. A good reminder to measure, never guess. I’m sure everyone knows this, but it never hurts to hear it again: for true performance testing, there is no substitute for testing on device. The simulator is nice for fast iterations and no hassle previews of your work, but its performance is usually completely different from the device. In the simulator, these shadowed labels render no problem. One thing that makes the iOS so nice and smooth and snappy is that it is hardware accelerated. The graphics chip takes on a lot of the work of layout and compositing, but the actual drawing of the images which are passed off to the graphics hardware is done on the CPU. No wonder the simulator running on my MacBook Pro has no trouble rendering these shadows, but the iPhone itself bogs down! Another interesting thing is that every now and then I’ve found the simulator to be slower than the real device. The point is, you just never know, so TEST ON A DEVICE! And USE INSTRUMENTS! Ok, that’s enough yelling for now.
Filed under: design, programming Tagged: CALayer, idevblogaday, UIKit
![]()
Posted by dwahlin at Dan Wahlin's WebLog
We’ve been seeing a sharp increase in the number of people interested in getting started with jQuery lately in our training and consulting business which is exciting since it’s such a great framework to use for client-side coding. If you’ve been fighting with cross-browser issues and want to make client-side development fun again then jQuery is a great way to go in my opinion.
One of the challenges with learning any new framework is knowing where to find documentation and good sources of examples. Although I normally rely on the standard documentation on the www.jQuery.com site, there are several other sources out there that can be helpful. Some of the sources are a bit dated, but they still provide a good way to find out more about core functionality. Here’s a quick list of the sites and extensions I’m aware of. If you know of others please let me know by adding a comment and I’ll update the list.
This is the main documentation site available for jQuery. It’s a great place to find details, but you’ll have to know where to look which can be frustrating sometimes for new developers.
This is a nice Chrome extension that adds jQuery API search support to Chrome’s omnibox (the URL/search textbox at the top of the browser). Simply type jq followed by a tab and then enter the function you’d like to get documentation on in the omnibox. The extension will search the APIs on the jQuery.com site and return matching results. Very handy….get it here.
This Chrome extension provides a quick way to search through jQuery documentation without having to open up a webpage. It’s not completely up-to-date but is quick and efficient for finding information about most functions.
Provides a great way to pull up the official documentation using a simplified navigation mechanism. I like how clean the documentation is and how well the search and navigation scheme works. They also have an offline version available which is handy when you don’t have access to the network.
james.padolsey.com/jquery/#v=git
This site provides a great way to see what’s happening inside the jQuery source code (a great way to learn various JavaScript tips and tricks). Simply type in the function you’d like to explore and the site will display the source code.
Another documentation site that provides a nice navigation scheme and clean view of the documentation. It’s a little outdated (covers jQuery 1.6).
This site provides some nice drill-down functionality to find out details about a particular function quickly and easily. It’s out dated but provides a quick way to find out about the core API functions.
This site is also a bit outdated, but if you’re looking to quickly find details on core functionality it makes it easy to drill-down into specific topics, see related functions, and then get details and samples about a given function.
If you’re interested in learning more about jQuery check out my jQuery Fundamentals course at Pluralsight.com.

Posted by Gabriel Wyner at Lifehacker
Lifehacker reader Gabriel Wyner was tasked with learning four languages in the past few years for his career as an opera singer, and in the process landed on “a pretty damn good method for language learning that you can do in limited amounts of spare time.” Here’s the four-step method that you can use, too (and you don’t have to invest hundreds in a language course like Rosetta Stone). More »
Posted by dwahlin at Dan Wahlin's WebLog
As the use of Ajax continues to grow in popularity it’s worth taking the time to think through how Ajax calls are structured and used in an application especially if re-use and maintenance are important. If you analyze a lot of the Ajax code out there you’ll likely find that calls to the server are scattered throughout scripts and pages. For example, if an Ajax call is made to get a list of jobs, a call is made directly in the script that needs the data. If another page/script needs the same type of data another Ajax call is made. This results in code duplication and complicates maintenance since Ajax calls aren’t consolidated.
While there’s certainly nothing wrong with this approach (it gets the job done after all), you can get better re-use out of your Ajax calls by consolidating them into JavaScript objects. In this post I’ll talk about how Ajax calls can be consolidated using JavaScript patterns and describe the benefits this approach provides.
JavaScript libraries such as jQuery make it so easy to make Ajax calls that we often don’t think much about the code being written and where it’s being used. For example, consider the following code that’s used to retrieve customers from a WCF service and update a page with the retrieved data:
$('#GetCustomersButton').click(function () { $.getJSON('../CustomerService.svc/GetCustomers', function (data) { var cust = data.d[0]; $('#ID').text(cust.ID); $('#FirstName').val(cust.FirstName); $('#LastName').val(cust.LastName); }); });
Although this code works fine, it can’t be re-used across other pages that may also need customer data. If another page or script needs the same data then the getJSON() call will have to be re-written since the manner in which the returned data is processed will more than likely be different. In addition to this potential problem, the code is added into a script that may have completely different responsibilities that are unrelated to calling a service.
In the object-oriented world we strive to follow the single responsibility principle when designing classes to avoid duplication and provide better re-use. Following this same principle in JavaScript code makes a lot of sense and can lead to better re-use, simplified maintenance, and better overall organization of code in an application. By placing Ajax calls into a re-useable JavaScript object we can use them throughout an application more easily, minimize duplicate code, and provide a better maintenance story. Before jumping into how Ajax calls can be consolidated, let’s review a key pattern called the Revealing Module Pattern that can be used to encapsulate JavaScript code.
There are several different patterns that can be used to structure JavaScript code and provide a way for functions to be encapsulated inside of class-like structures (given that JavaScript doesn’t officially support the concept of a class). One pattern that can be used is the Revealing Module Pattern. By using the pattern you can encapsulate variables and functions into an object, achieve re-use, simplify maintenance, and can also help avoid naming collisions. There are several other patterns such as the Prototype Pattern and Revealing Prototype Pattern that can be used (to name just two) but the Revealing Module Pattern provides a simple way to get started creating JavaScript objects that are similar in purpose to C# or Java classes.
The following code shows an example of some simple code that has no structure applied to it (I call it “Function Spaghetti Code”). With this approach variables and functions are scattered throughout a file with no rhyme or reason as to how they relate to each other. All of the variables and functions defined this way are automatically placed in the global scope which can lead to naming collisions.
$('#GetCustomersButton').click(function () { $.getJSON('../CustomerService.svc/GetCustomers', function (data) { var cust = data.d[0]; $('#ID').text(cust.ID); $('#FirstName').val(cust.FirstName); $('#LastName').val(cust.LastName); }); });
Listing 1. Function-based JavaScript Code with no encapsulation.
Listing 2 shows this same code refactored to follow the Revealing Module Pattern. In this simple example the code is encapsulated in an object named car. Following this pattern allows the code to be organized, variables and functions to be taken out of the global scope, and a re-useable object to be defined that can be used in one or more pages or applications.
var engine = 'V8'; function start() { alert('Car started ' + engine + ' engine'); } function stop() { alert('Car stopped ' + engine + ' engine'); } function turn() { alert('Car turned') }
Listing 2. Organize functions in an object to provide encapsulation, re-use, easier maintenance, and to help avoid naming collisions.
Looking through the code in Listing 2 you’ll see that 3 functions are defined including start(), stop(), and turn(). All three are publicly exposed to consumers using the return object that’s defined (an object literal). Any functions not listed in the return object are inaccessible to consumers making them similar to private members in object-oriented languages. Since the car object is self-invoked (note the parenthesis at the end of Listing 2) you can call it directly using code such as the following:
car.start(); car.stop(); car.turn();
If you want to create a new instance of car the code in Listing 3 can be used instead of the code shown in Listing 2. Notice that the Car object starts with an upper-case character so that the consumer knows to create a new instance of the object to use it. This is a common convention being used more and more among JavaScript developers.
var Car = function (engine) { var start = function () { alert('Car started ' + engine + ' engine'); }, stop = function () { alert('Car stopped ' + engine + ' engine'); }, turn = function () { alert('Car turned'); }; return { start: start, stop: stop, turn: turn }; };
Listing 3. Using the Revealing Module Pattern to create a Car object that can be created using the “new” keyword.
To use the Car object the following code can be written:
var car = new Car('V8'); car.start(); car.stop(); car.turn();
If you only need one object in memory as an application is running the code shown in Listing 2 works well. If you need multiple instances of an object the self-invoking parenthesis can be removed as shown in Listing 3.
Now that you’ve seen how the Revealing Module Pattern can be used to structure JavaScript code, let’s see how it can encapsulate Ajax functions into an object.
A sample application named Account at a Glance (download it here – an image from the application is shown below) built to demonstrate several HTML5, jQuery, and general JavaScript concepts relies on the Revealing Module Pattern to consolidate Ajax calls into a single object that can be re-used throughout the application. By following this pattern, an Ajax call used to retrieve market quotes can be defined in one place and then called from other scripts that may need the data. This approach provides several benefits including more modular, re-useable, and maintainable code. If something changes with an Ajax call you can go to one place to make the core modifications rather than searching through multiple scripts and pages to find where changes need to be made.
To access market quote data in the application the following call could be made as data is needed in a given script:
$.getJSON('/DataService/GetQuote', { symbol: sym }, function (data) { //process data here });
Although this code works, it’s much better from a re-use and maintenance standpoint to consolidate calls into an object. Listing 4 shows an example of an Ajax-specific object named dataService that the Account at a Glance application uses to retrieve different types of JSON data from the server.
var dataService = new function () { var serviceBase = '/DataService/', getAccount = function (acctNumber, callback) { $.getJSON(serviceBase + 'GetAccount', { acctNumber: acctNumber }, function (data) { callback(data); }); }, getMarketIndexes = function (callback) { $.getJSON(serviceBase + 'GetMarketIndexes', function (data) { callback(data); }); }, getQuote = function (sym, callback) { $.getJSON(serviceBase + 'GetQuote', { symbol: sym }, function (data) { callback(data); }); }, getTickerQuotes = function (callback) { $.getJSON(serviceBase + 'GetTickerQuotes', function (data) { callback(data); }); }; return { getAccount: getAccount, getMarketIndexes: getMarketIndexes, getQuote: getQuote, getTickerQuotes: getTickerQuotes }; } ();
Listing 4. Consolidating Ajax calls into a dataService object.
The dataService object follows the Revealing Module Pattern discussed earlier to encapsulate the various functions. A single instance is created initially at runtime (the dataService function is self-invoked as the script initially loads) that exposes four functions responsible for getting account, market, quote, and ticker data from the server.
Looking through each function in the dataService object you’ll notice that they all accept a callback parameter. Because each function is re-useable, it won’t know how to handle the data that’s retrieved from a given service – processing of data is unique to the caller of the function. As a result, each function in dataService allows the caller to pass a callback function that is invoked once the data returns from the service to the client. An example of calling the dataService object’s getAccount() function is shown next:
dataService.getAccount(acctNumber, renderAccountTiles);
When the data is returned the getAccount() function will invoke the renderAccountTiles callback function shown in Listing 5.
renderAccountTiles = function (data) { $('div.tile[id^="Account"]').each(function () { sceneStateManager.renderTile(data, $(this), 500); }); }
Listing 5. The renderAccountTiles() function handles data returned from the call to dataService.getAccount().
Note that a nested/inline callback function could be passed to getAccount() as well as shown next:
dataService.getAccount(acctNumber, function (data) { //Process data here });
Anytime a script in the application needs to retrieve data from the server a call can be made to one of the dataService object’s functions and required parameters can be passed along with the callback. This technique provides a flexible way for Ajax functionality to be consolidated into an object while remaining flexible as far as callbacks go.
This technique can be applied to other parts of an application as well to create additional objects that encapsulate related variables and functions. By focusing on objects rather than functions you can more efficiently organize code in an application and achieve many of the benefits mentioned earlier such as better re-use and simplified maintenance. Eliminating Function Spaghetti Code is definitely a good thing.
If you’d like additional details about structuring JavaScript code or building an end-to-end application check out my Structuring JavaScript Code or Building an ASP.NET MVC, EF Code First, HTML5, and jQuery courses from Pluralsight.
Posted by Thorin Klosowski at Lifehacker
Jet lag can be difficult to overcome no matter how used to travelling you are, but blogger and illustrator Yumi Sakugawa has put together a simple start to finish graphic to help you overcome even the longest flights. More »
Posted by Doug Davies at iDevBlogADay
In a previous blog entry I had mentioned that I combined my Full and Lite versions of each of my apps into one XCode project using targets. This was something that pre-XCode 4 was pretty hard to do, thus my decision to keep them as separate projects until recently.
Another reason to create multiple targets would be to keep your iPhone and iPad versions in the same project. This probably becomes even more important nowadays if you don’t wish to go the Universal App route and prevent retina assets app bloat. Plus it gives you the option of pricing your iPad app differently than your iPhone app if you choose to do so.
I didn’t go into much detail the previous time around other than to give a few quick pointers. This time I’ve created a sample project and will guide you through step-by-step with screen captures where appropriate. The project can be found here (you’ll need it because I’m not going to go through every single step in this tutorial).
The first thing I did was create a new “Single View” project.
This created a target with the same name as the project.
I really wanted to create 2 targets with different names than the project. So I created 2 new “Single View Application” targets (File->New->Target). The first one I called MultiTargetIphone and the second MultiTargetIpad, making sure to select the right “Device Family” for both.
I then removed the original MultiTarget target, scheme, and directory. You do this by selecting Product->Manage Schemes. Click the minus sign to remove MultiTarget. Then select the target in the TARGET view, right click, and delete. Also remove it from the files view and the physical directory in the project (show in finder). If anyone has a better way to remove a target and all it’s files, let me know. It seems like a lot of areas to remove.
Here’s what my project looked like after this step
And in Finder
To prove that these are indeed 2 different targets and binaries I’m going to add some shared code and assets as well as specific target code and assets. When we’re done we’ll examine the resulting bundles and make sure only the necessary assets are included. When adding files and assets make sure you specify what target they should be included in.
or you can do this after the fact in the File Inspector panel
In this example I’m using a separate XIB file per target. I’m going to put 2 buttons in each. One button will call a target specific IBAction and the other will call an IBAction that will use a shared class to perform it’s behavior. Both targets include SharedStuff.m and shared.png, however they each have their own ViewController that handles the specific behaviors for that target as well as their own button images (ipad.png and iphone.png).
The one thing I did notice is that Interface Builder doesn’t seem to honor the “Target Membership” settings. That is, when I’m editing the XIB for the iPad it allows me to select iphone.png as the background button image even though I only added that file to the iPhone target. The button DOES end up empty as expected when you run the executable (because the png file is not included in the bundle), but just be aware interface builder may be showing you things it shouldn’t (let me know if you have a different understanding of this).
I’m not going to go into the details of wiring up the IBActions, building the UI, or writing the code in the action. You have the source and can play around with that. Here’s what my project structure now looks like.
My directory structure in Finder looks like this
You’ll notice I also added icon.png and icon-72.png for both the iPhone and iPad. You can select the icon to use in the target’s summary panel
Ok, now let’s run the 2 targets. First select the iPad one and run it on the iPad simulator.
You’ll see the following
The top button is using ipad.png to display it’s contents. The bottom button is using shared.png. Clicking on each will call the appropriate IBAction in the ViewController and display an alert dialog. The shared one will use SharedStuff which is common code (and asset) shared by both targets.
Now let’s run the iPhone one in the iPad simulator to prove that they are indeed 2 different binaries. You’ll know this because the iPhone version will run in 1x mode and not take up the full screen.
You’ll also notice two different icons on the SpringBoard.
Ok, but how do you know the bundles only include what is necessary for each platform? One way is to look at the “Build Phases”.
Notice that the iPad target includes it’s version of main.m, AppDelegate.m, and ViewController.m, and includes the shared SharedStuff.m. But it doesn’t reference any of the code files for the iPhone target. In the resources it has it’s own InfoPlist.strings, ViewController.xib, and ipad.png, and shares shared.png, but doesn’t reference iphone.png or it’s interface builder files.
Another option is to build for the device and use PhoneView to inspect the package contents.
You don’t see any of the iPhone assets in the iPad bundle.
Whew… I hope that helps understanding how to build an iOS app that can target multiple devices separately and yet share common assets. Or you might use it to provide full and lite versions of your app. You’d just add a LITE_VERSION compiler flag to the build settings for your lite version and ifdef your code accordingly.
There really is no reason not to try and combine different versions of your app into one project now that Apple has made it easy. While this use to be hard before XCode 4 it’s obvious Apple has given this considerable thought since then.
UPDATE: Last weekend I submitted Jiggle Balls Studio to Apple. It’s the update to Jiggle Balls HD that is now FREE and supports In-App Purchases. I’m still waiting for it to be approved, but in the meantime you can go get the previous version for FREE and get yourself ready for the update. Enjoy!