Archives for category: UI

Full Source code: https://github.com/boctor/idev-recipes/tree/master/SideSwipeTableView

Problem:

The Twitter iPhone app pioneered the ability to swipe on a tweet and have a menu appear, letting you do things like reply or favorite the tweet.

Tweets in the Twitter app are table view cells in a table view. How do we recreate this feature and add the ability to side swipe on table view cells?

Solution:

This feature has two distinct parts. The first is detecting that the user swiped on the table. The second is animating in and animating out the menu view.

Detecting swipes in iOS 4

iOS 4 introduced Gesture Recognizers which make gestures like swiping, tapping and pinching very east to detect. Specifically we can create a couple of UISwipeGestureRecognizer objects, one for the right direction and another for the left detection and attach them to the table view:

// Setup a right swipe gesture recognizer
UISwipeGestureRecognizer* rightSwipeGestureRecognizer = [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRight:)] autorelease];
rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
[tableView addGestureRecognizer:rightSwipeGestureRecognizer];

// Setup a left swipe gesture recognizer
UISwipeGestureRecognizer* leftSwipeGestureRecognizer = [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeLeft:)] autorelease];
leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
[tableView addGestureRecognizer:leftSwipeGestureRecognizer];

Now when the user swipes left or right anywhere in the table, our swipeRight: or swipeLeft: methods will get called. The touch handling code that tracks the user’s finger and figures out their intent is blissfully handled for us.

Detecting swipes in iOS 3

When this feature was introduced in what was then the Tweetie app, it worked in iOS 3 well before iOS 4 was released. You might smartly argue that if iOS 3 currently makes up 1-2% of users out there it isn’t worth developing for and I admit this is a valid point. Still it’s an interesting technical mystery and that’s just the kind of thing we love solving!

You might have thought like I did, that the Twitter app must have implemented its own touch handling, guessing based on the location of your finger whether you were trying to do a swipe, but this is wrong.

In the Twitter app it doesn’t matter if you swipe left or swipe right, the animation of the menu always happens from left to right. This is the same behavior as the editing of table view cells and it turns out this is how the Twitter app does it: It hijacks the built in swipe to delete feature of table view cells. There are 3 parts to making this work:

1. Enabling swipe to delete

Per Apple’s documentation:

To enable the swipe-to-delete feature of table views (wherein a user swipes horizontally across a row to display a Delete button), you must implement the tableView:commitEditingStyle:forRowAtIndexPath: method

So the first step is to implement the tableView:commitEditingStyle:forRowAtIndexPath: method.

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
}

The method doesn’t have to do anything. Once it is implemented, you’ll be able to side swipe on a cell and the Delete button will appear.

2. Disabling the Delete button

Apple’s Inserting and Deleting Rows and Sections documentation indicates that when you explicitly put a table in editing mode by calling setEditing:animated:, the same message is then sent to each of the visible cells.

The documentation for a table view cell’s setEditing:animated: indicates that when this method is called, insertion/deletion control are animated in.

So disabling the Delete button turns out to be relatively simple: Override the table view cell’s setEditing:animated: and don’t call the superclass’s implementation.

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
  // We suppress the Delete button by explicitly not calling
  // super's implementation
  if (supressDeleteButton)
  {
    // Reset the editing state of the table back to NO
    UITableView* tableView = [self getTableView:self];
    tableView.editing = NO;
  }
  else
    [super setEditing:editing animated:animated];
}

3. Getting notified when a swipe occurred

Apple’s docs for tableView:willBeginEditingRowAtIndexPath: are crystal clear: This method is called when the user swipes horizontally across a row.

The implementation of this method in iOS 3 is a parallel to the swipeLeft: and swipeRight: methods we registered with UISwipeGestureRecognizers under iOS 4. When any of these methods are called, we know that a swipe happened and we are ready to animate in the menu.

Animating in the menu view

Before we animate in the menu, we first add it as a subview of the table view.

As you can see in the image at the top of this post, we are animating the existing cell content offscreen while simultaneously animating in the menu. Here is a rough illustration of how both the cell content and the menu have to animate in sync during a left to right animation:

So we first set the frame of the menu, placing it offscreen. Depending of the direction, we’d put it offscreen on the right or left side of the table. Next we’d start an animation block and set the frame of the menu to be at 0 x-offset. Inside the same animation block we also set the cell’s frame to be offscreen on the other side of the table.

- (void) addSwipeViewTo:(UITableViewCell*)cell direction:(UISwipeGestureRecognizerDirection)direction
{
  // Change the frame of the side swipe view to match the cell
  sideSwipeView.frame = cell.frame;

  // Add the side swipe view to the table
  [tableView addSubview:sideSwipeView];
  
  // Remember which cell the side swipe view is displayed on and the swipe direction
  self.sideSwipeCell = cell;
  sideSwipeDirection = direction;

  // Move the side swipe view offscreen either to the left or the right depending on the swipe direction
  CGRect cellFrame = cell.frame;
  sideSwipeView.frame = CGRectMake(direction == UISwipeGestureRecognizerDirectionRight ? -cellFrame.size.width : cellFrame.size.width, cellFrame.origin.y, cellFrame.size.width, cellFrame.size.height);

  // Animate in the side swipe view
  animatingSideSwipe = YES;
  [UIView beginAnimations:nil context:nil];
  [UIView setAnimationDuration:0.2];
  [UIView setAnimationDelegate:self];
  [UIView setAnimationDidStopSelector:@selector(animationDidStopAddingSwipeView:finished:context:)];
  // Move the side swipe view to offset 0
  sideSwipeView.frame = CGRectMake(0, cellFrame.origin.y, cellFrame.size.width, cellFrame.size.height);
  // While simultaneously moving the cell's frame offscreen
  // The net effect is that the side swipe view is pushing the cell offscreen
  cell.frame = CGRectMake(direction == UISwipeGestureRecognizerDirectionRight ? cellFrame.size.width : -cellFrame.size.width, cellFrame.origin.y, cellFrame.size.width, cellFrame.size.height);
  [UIView commitAnimations];
}

Animating out the menu view

When the menu is animated away, there is a little bounce of the cell content as it comes back into view.

Here is another rough illustration showing the three animations that make up a bounce, showing at each step where the cell content and menu are:

There are multiple ways we can achieve this animation. One is CAKeyframeAnimation where you specify a path and the animation follows that path.

Instead the code simply chains together the 3 separate animations. Since we might care about iOS 3, we don’t use animation blocks, but instead use begin/commit animation methods and register an animation stop selector where we start the next animation.

Just like we did when animating the menu in, at each step we animate both the menu as well as the cell to give the illusion that the cell content is pushing the menu out of view.

UPDATE: It was pointed out on Hacker News that the Twitter app actually puts the menu behind the cell and then only animates the cell content in and out. The menu isn’t animated at all. I’ve updated the code so that by default it now does this style of animation. If you really liked the pushing behavior where both the menu and cell content are animated, there is a PUSH_STYLE_ANIMATION #define that you can set to YES to get it back.

Full Source code: https://github.com/boctor/idev-recipes/tree/master/SideSwipeTableView

Tweet This!Hacker NewsShare on Facebook

Advertisement


Last week WordPress founding developer Matt Mullenweg was interviewed by John Battelle at SXSW where he was startlingly candid about the shortcomings of WordPress’s iPhone app

“Twitter inspired us to start taking mobile seriously,” he added. “You open it [Twitter’s app] at any time and instantly start reading your friends’ tweets. If you open our app you get a blank screen.”
Mullenweg was startlingly candid about the shortcomings of WordPress’s iPhone app, which he described as “not good yet.” His engineers are working to improve it, he added.

Not Good Yet

I’m a big WordPress fan, having used it for years on my personal blog and more recently here on iDevRecipes. I tried the WordPress iPhone app a while back and I’d wholeheartedly agree with Matt that it’s “not good yet.”

Now just as Matt said, the WordPress Mobile team is working on it. Just yesterday, they released version 2.7 of the app with over 100 bug fixes and UI improvements like pull to refresh.

Making it Great

But Matt’s comments got me thinking on how to make the WordPress app really great. Most iPhone apps initially focus on content consumption with a splash of account management. The thinking is that users are much more likely to consume on these devices.

The WordPress app is actually open sourced and you can see that it uses the WordPress XML-RPC API which predated the iPhone to let you manage your blog.

I think this XML-RPC API nudged the WordPress iPhone app towards a full blown account management app. But where is the content consumption? (reading the comments on your posts doesn’t count!)

Reimagined Around Content Consumption

So my first thought was to reimagine the app around content consumption. WordPress.com has a bunch of great curated content. They highlight posts in their Freshly Pressed section and they categorize blogs based on tags.

A little sketching, thinking and poking around WordPress.com and here is what I came up with:

  • First convert the app to a tab based app
  • Fill the first tab with the Freshly Pressed content
  • Fill the second tab with Tags, letting you explore the tags and then see blogs associated with each tag
  • In the third tab put Posts I like. You’d be able to add to this list either on WordPress.com or by liking posts from within the app
  • In the fourth tab put Subscriptions, letting you see the newest posts from the blogs that you subscribe to (Subscriptions are like RSS feeds for non-techies)
  • Take the existing app and put it under a My Blogs tab at the end of the tab bar

Prototype Implementation

Of course this is an iOS development blog, and we can’t have a post without code! So I implemented the first two items in the list. Using our previous Twitter custom tab bar recipe I converted the main view of the app to be tab bar based app. Next I added the Freshly Pressed content to the first tab.

Freshly Pressed

Normally when displaying existing content in an iPhone app, you can’t go wrong with RSS feeds. Freshly Pressed has an RSS feed, but it just displays the first page of content. Also, the image for each featured post is offset using a background-position CSS property that the RSS feed doesn’t expose.

Scraping

So I did what seemed reasonable at the time: I wrote a ruby script that scraped the Freshly Pressed pages and put some JSON up on S3. Now keep in mind that we’re just experimenting here and we can easily swap this scraping out for a real Freshly Pressed API.

Some interesting things about the ruby script: The images uses either a WordPress image server to resize the original images or an imgpress WordPress service to convert the blog home page to an image, and in both cases I change the width from the 223 pixels the web site uses to 320 pixels so the images look nice on the iPhone. After increasing the size from 223 to 320, I also have to increase the pixel offset for each image. For example, if the offset was -30 pixels for the original image, then the offset for the new image is -30 * (320/223).

Without a real design, my first cut iteration of the table view cells is to mirror the look of the web site, including the colors, fonts and general layout

Tapping on each cell loads the blog post in a UIWebView

What do you think?

If you were to imagine a really great WordPress iPhone app, what would you come up with?
Are there things about this design/implementation you like/don’t like?

Let me know in the comments!

Full Source code: https://github.com/boctor/idev-recipes/tree/master/WordPressReimagined

Tweet This!Hacker NewsShare on Facebook

Full Source code: https://github.com/boctor/idev-recipes/tree/master/CustomBackButton

Problem:

Apps like Instagram, Reeder and DailyBooth have a UINavigationBar with custom background and sometimes custom back buttons. How do we build a similar custom UINavigationBar?

Solution:

In our recipe for Recreating the iBooks wood themed navigation bar we added a wood  image as a subview of UINavigationBar. This worked but it turns out that we were lucky.

If we had tried to push another view controller onto our UINavigationController we would’ve ended up with a UINavigationBar that has nothing but our wood image. This is because as the standard UINavigationBar implementation adds items, it also then sends them to the back of its view hierarchy. So even if we add our custom image to the bottom of the UINavigationBar view hierarchy, the rightBarButtonItem, titleView and leftBarButtonItem end up below the custom image and out of sight.

The nav bar background

We need a new, more flexible solution: Instead of adding to a UINavigationBar’s view hierarchy we will subclass UINavigationBar. We’ll override UINavigationBar’s drawRect and draw our custom background image directly:

// If we have a custom background image, then draw it, othwerwise call super and draw the standard nav bar
- (void)drawRect:(CGRect)rect
{
  if (navigationBarBackgroundImage)
    [navigationBarBackgroundImage.image drawInRect:rect];
  else
    [super drawRect:rect];
}

Any time navigationBarBackgroundImage changes we also need to call [self setNeedsDisplay] so the new background image is properly drawn.

A couple of methods allow us to set or clear the background image:

// Save the background image and call setNeedsDisplay to force a redraw
-(void) setBackgroundWith:(UIImage*)backgroundImage
{
  self.navigationBarBackgroundImage = [[[UIImageView alloc] initWithFrame:self.frame] autorelease];
  navigationBarBackgroundImage.image = backgroundImage;
  [self setNeedsDisplay];
}

// clear the background image and call setNeedsDisplay to force a redraw
-(void) clearBackground
{
  self.navigationBarBackgroundImage = nil;
  [self setNeedsDisplay];
}

Multiple nav bar backgrounds

In most cases, you’ll have a single custom background image that you’ll set once.

If you need to change the custom background more than once, say every time the user enters a new section, then simply call setBackgroundWith every time you want the nav bar’s background to change.

The source code for this recipe is one app with a single UINavigationController and a table row for each of the apps: InstagramReeder and DailyBooth. When you select a row, we push a view controller that calls setBackgroundWith to set the background image for each app.

Custom back button

In the iBooks recipe we created a custom UIBarButtonItem by creating a button with a stretchable image and adding the button as the customView of UIBarButtonItem.

We do the same thing here except we use an image has an arrow on the left side and we adjust the button’s titleEdgeInsets to center the text properly.

The backButtonWith:highlight:leftCapWidth: convenience method on our CustomNavigationBar class creates a back button which we can then add as the leftBarButtonItem. This replaces the built in back button.

To resize our custom back button to match width of the text, we use UILabel’s sizeWithFont to measure the width of the text and resize the button appropriately.

Trying it out

Just like the standard back bar button implementation, the CustomNavigationBar will set the title of the back button to the title of the previous controller on the UINavigationController stack.

The source code for this recipe also lets you dynamically change the back button text after a view controller is pushed onto the UINavigationController stack. The back button resizes as needed and you get to see and experiment with different text and button widths.

Full Source code: https://github.com/boctor/idev-recipes/tree/master/CustomBackButton

Tweet This!Hacker NewsShare on Facebook

Full Source code: https://github.com/boctor/idev-recipes/tree/master/CustomTabBar

Problem:

The Twitter iPhone App has a custom tab bar that is shorter than the standard tab bar, doesn’t have titles for the tab bar items and has a blue glow indicating when a section has new content. We want to recreate this custom tab bar.

Solution:

Just like segmented controls, the best way to customize the tab bar is to build it from scratch. In fact we’re going to start by using a recipe similar to what we used for custom segment controls:

  • Create a button for every tab bar item.
  • Manage the touches on the buttons so when one is selected, the others are deselected.

But how do we recreate the look of the buttons and how about that nice background for the tab bar?

The tab bar background

Looking at the images of the Twitter app, we find the TabBarGradient.png image which is 22px, exactly half the 44px height of this custom tab bar.

Taking a screenshot of the Twitter app and looking at it carefully reveals how the background is built:

  • The top half is a stretchable image of TabBarGradient.png
  • The bottom half is simply solid black

The custom tab bar asks its delegate for the background image and here is how we build it:

// Get the image that will form the top of the background
UIImage* topImage = [UIImage imageNamed:@"TabBarGradient.png"];

// Create a new image context
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, topImage.size.height*2), NO, 0.0);

// Create a stretchable image for the top of the background and draw it
UIImage* stretchedTopImage = [topImage stretchableImageWithLeftCapWidth:0 topCapHeight:0];
[stretchedTopImage drawInRect:CGRectMake(0, 0, width, topImage.size.height)];

// Draw a solid black color for the bottom of the background
[[UIColor blackColor] set];
CGContextFillRect(UIGraphicsGetCurrentContext(), CGRectMake(0, topImage.size.height, width, topImage.size.height));

// Generate a new image
UIImage* resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return resultImage;

The buttons

The buttons have the following visual states:

  • Drawn in gray when unselected
  • Drawn with blue gradient when selected
  • Embossed border is drawn around the selected item

A button has both an image and a background image and they can both be set for the various control states. When a button is selected, the blue gradient appears to be on top and the embossed border is behind it. So here is how we’ll setup the button:

  • The button’s image for the normal state will be gray
  • The button’s image for the selected/highlighted state will be blue
  • The button’s background image for the selected/highlighted state will be the embossed border

The images for the tab bar items

A standard UITabBar only uses the alpha values of the tab bar item images. It doesn’t matter what color the images are, they will always appear in gray and blue. For our custom tab bar to be truly reusable, it will need to do the same thing.

But how exactly do we do this? It takes several steps:

  1. First we take the image and use CGContextClipToMask to generate a new image that has a white background and black content:
  2. Next we take this black and white image and use CGImageMaskCreate to create an image mask.
  3. Finally we combine the image mask with a background color.

For every tab bar item we generate two images: one with a solid gray background and another with a blue gradient background.

The blue glow

The blue glow is an image that is simply added to each button as a subview. In the Twitter app, a tab bar item will get a blue glow after the app has downloaded new content. It is a visual cue that there is more content in that section.

Our custom tab bar asks its delegate for the glowImage and it exposes a couple of methods to manage the glow: glowItemAtIndex and removeGlowAtIndex.

The current tab bar indicator

When a tab bar item is selected, a triangle at the top of the tab bar animates into place. We covered this animation in an earlier post. We use the code from that post to get the same animation for the custom tab bar.

Full Source code: https://github.com/boctor/idev-recipes/tree/master/CustomTabBar

Tweet This!Hacker NewsShare on Facebook

Full Source code: https://github.com/boctor/idev-recipes/tree/master/VerticalSwipeArticles

Problem:

The Reeder iPhone App lets you pull up to see the title of the next article. If you pull up far enough the arrow rotates and the next article animates into view. We want to recreate this UI.

Solution:

If you don’t pull up far enough, the article bounces back into view and that is a very strong clue that we are dealing with a UIScrollView.

A UIScrollView is used to display content that is larger than the application’s window. You tell it the contentSize of your content and it manages scrolling within the content. When you get to the edge of the content, the scroll view bounces to let you know you’ve reached the edge.

The header and footer views

Normally when you pull up at the edge of a scroll view empty space appears, but in the Reeder app, the title of the next article appears along with an arrow. To recreate this we’ll create a scroll view with a contentSize that is the same as the scroll view. Then we’ll tell the scroll view to alwaysBounceVertical. This causes a view that bounces vertically when you pull up or down.

Next we’ll add a header view as the subview of the scroll view and set it’s frame to be right above the scroll view and we’ll add a footer view as the subview of the scroll view and set it’s frame to be right below the scroll view. The header and footer are offscreen but when you pull up or down, they get pulled into view.

Subclassing UIScrollView

In addition to trying to figure out how to recreate the feature, we need to also figure out how to structure our code. The most reusable part of this feature is the ability to swipe up and down to see another article while seeing a preview of the previous/next article. We’ve already determined that we’ll be using a scroll view that we’ve customized so it seems logical that we would create a subclass of UIScrollView.

Animating the header and footer views

The arrows in the header and footer rotate to let the user know that when they lift their finger, the previous/next article will be shown. When the view has been scrolled past some distance we need to trigger this arrow rotation.

To accomplish this we will listen to the UIScrollViewDelegate’s scrollViewDidScroll message and check the scroll view’s contentOffset. This means that our UIScrollView subclass will have itself as its delegate. This sounds odd but works just fine.

Our subclass will send out 4 messages:

  • headerLoadedInScrollView
  • headerUnloadedInScrollView
  • footerLoadedInScrollView
  • footerUnloadedInScrollView

A header/footer is loaded when the user pulls down or up past the height of the header/footer. It is unloaded when they pull back and hide part of the header/footer. So with one arrow image, this is how we animate the arrow rotation:

- (void) rotateImageView:(UIImageView*)imageView angle:(CGFloat)angle
{
  [UIView beginAnimations:nil context:nil];
  [UIView setAnimationDuration:0.2];
  imageView.transform = CGAffineTransformMakeRotation(DegreesToRadians(angle));
  [UIView commitAnimations];
}
-(void) headerLoadedInScrollView:(VerticalSwipeScrollView*)scrollView
{
  [self rotateImageView:headerImageView angle:0];
}

-(void) headerUnloadedInScrollView:(VerticalSwipeScrollView*)scrollView
{
  [self rotateImageView:headerImageView angle:180];
}

-(void) footerLoadedInScrollView:(VerticalSwipeScrollView*)scrollView
{
  [self rotateImageView:footerImageView angle:180];
}

-(void) footerUnloadedInScrollView:(VerticalSwipeScrollView*)scrollView
{
  [self rotateImageView:footerImageView angle:0];
}

Animating the previous and next page

The UIScrollViewDelegate’s scrollViewDidEndDragging message lets us know when the user has lifted their finger after dragging. To animate the next page, we place the page below the footer and inside of an animation block place it on screen. This results in a nice up animation.

if (_footerLoaded) // If the footer is loaded, then the user wants to go to the next page
{
  // Ask the delegate for the next page
  UIView* nextPage = [externalDelegate viewForScrollView:self atPage:currentPageIndex+1];
  // We want to animate this new page coming up, so we first
  // Set its frame to the bottom of the scroll view
  nextPage.frame = CGRectMake(0, nextPage.frame.size.height + self.contentOffset.y, self.frame.size.width, self.frame.size.height);
  [self addSubview:nextPage];

  // Start the page up animation
  [UIView beginAnimations:nil context:nextPage];
  [UIView setAnimationDuration:0.2];
  [UIView setAnimationDelegate:self];
  [UIView setAnimationDidStopSelector:@selector(pageAnimationDidStop:finished:context:)];
  // When the animation is done, we want the next page to be front and center
  nextPage.frame = self.frame;
  // We also want the existing page to animate to the top of the scroll view
  currentPageView.frame = CGRectMake(0, -(self.frame.size.height + headerView.frame.size.height), self.frame.size.width, self.frame.size.height);
  // And we also animate the footer view to animate off the top of the screen
  footerView.frame = CGRectMake(0, -footerView.frame.size.height, footerView.frame.size.width, footerView.frame.size.height);
  [UIView commitAnimations];

  // Increment our current page
  currentPageIndex++;
}

We also register a callback for when this animation is done and make sure our header and footer are in place for the next time the user pulls the scroll view up or down.

UIWebViews are unique

Our UIScrollView subclass calls the delegate’s viewForScrollView:atPage to get the actual pages. Life would be simple if we could return a static page like say an image, but in the real world it is more likely that you will be returning a UIWebView to accommodate things like titles that may wrap.

The sample app uses a JSON feed of the top paid apps in the App Store and uses a UIWebView to display each page.

No matter how simple the html that you are displaying in a UIWebView, the rendering will not be instantaneous and there will always be an overhead of setting up the UIWebView. If every time viewForScrollView:atPage is called you created a new  UIWebView with html, then as this page is getting animated into view, the rendering will not have completed. The net result will be that the scroll animation will show a blank white page instead of the actual content.

To deal with this the sample app keeps around a previousPage and nextPage UIWebViews. When asked for page 1, the sample preloads previousPage with page 0 and nextPage with page 2. If there are other caching techniques you think would work here, please share your thoughts in the comments.

Full Source code: https://github.com/boctor/idev-recipes/tree/master/VerticalSwipeArticles

Tweet This!Hacker NewsShare on Facebook

Full Source code: https://github.com/boctor/idev-recipes/tree/master/TabBarAnimation

Problem:

The Twitter iPhone App has a small arrow indicator above the tab bar that animates when a tab is selected. We want to recreate this animation.





Solution:

The arrow is simply another image added on top of the tab bar which is animated every time the tab selection changes. So we have two tasks:

  • Add the arrow on top of the tab bar. This is similar to what we did in our last recipe.
  • Animate the arrow when a new tab is selected.

To add arrow on top of the tab, we have to figure out the proper horizontal and vertical locations.

Vertical Location

The vertical location is always the same so we’ll figure it out just once. To calculate the vertical location, we start at the bottom of the window, go up by height of the tab bar, go up again by the height of arrow and then come back down 2 pixels so the arrow is slightly on top of the tab bar:

CGFloat verticalLocation = self.window.frame.size.height - tabBarController.tabBar.frame.size.height - tabBarArrowImage.size.height + 2;

Horizontal Location

The horizontal location will change depending on which tab bar is currently selected. So we’ll write a method that given a tab index figures out the horizontal location.
There is nothing too complicated here: We divide the width of the tab bar by the number of items to calculate the width of a single item. We then multiply the index by the width of single item and add half the width of an item so the arrow lands in the middle:

- (CGFloat) horizontalLocationFor:(NSUInteger)tabIndex
{
  // A single tab item's width is the entire width of the tab bar divided by number of items
  CGFloat tabItemWidth = tabBarController.tabBar.frame.size.width / tabBarController.tabBar.items.count;
  // A half width is tabItemWidth divided by 2 minus half the width of the arrow
  CGFloat halfTabItemWidth = (tabItemWidth / 2.0) - (tabBarArrow.frame.size.width / 2.0);

  // The horizontal location is the index times the width plus a half width
  return (tabIndex * tabItemWidth) + halfTabItemWidth;
}

Add the arrow on top of the tab bar

On app startup we add the arrow on top of the selected tab. Our sample app doesn’t remember which tab you had selected before you quit, so we always start at index 0 ([self horizontalLocationFor:0]):

- (void) addTabBarArrow
{
  UIImage* tabBarArrowImage = [UIImage imageNamed:@"TabBarNipple.png"];
  self.tabBarArrow = [[[UIImageView alloc] initWithImage:tabBarArrowImage] autorelease];
  // To get the vertical location we start at the bottom of the window, go up by height of the tab bar, go up again by the height of arrow and then come back down 2 pixels so the arrow is slightly on top of the tab bar.
  CGFloat verticalLocation = self.window.frame.size.height - tabBarController.tabBar.frame.size.height - tabBarArrowImage.size.height + 2;
  tabBarArrow.frame = CGRectMake([self horizontalLocationFor:0], verticalLocation, tabBarArrowImage.size.width, tabBarArrowImage.size.height);

  [self.window addSubview:tabBarArrow];
}

Animate the arrow when a new tab is selected

A UITabBarController delegate gets notified every time a view controller was selected. We’ll use this as the trigger for starting the animation.

The actual animation is very simple. We use animation blocks available on every view.

If you haven’t used animation blocks before, here is a simple description:

  • Before you start the animation block set the frame of the item you want to animate to the start location.
  • Inside the animation block set the frame of the item you want to animate to the end location.

That’s all you have to do. The OS figures out the intermediate frames and does the actual animation for you. Doesn’t get simpler than that.

The arrow is already at the location we want it to animate from, so we don’t have to do anything before we start the animation block.

Inside the animation block block, all we have to do is set the final location of the arrow. So we take the existing frame of the arrow and change its horizontal location based on the newly selected tab index:

- (void)tabBarController:(UITabBarController *)theTabBarController didSelectViewController:(UIViewController *)viewController
{
  [UIView beginAnimations:nil context:nil];
  [UIView setAnimationDuration:0.2];
  CGRect frame = tabBarArrow.frame;
  frame.origin.x = [self horizontalLocationFor:tabBarController.selectedIndex];
  tabBarArrow.frame = frame;
  [UIView commitAnimations];
}

There a couple of things you can play around with to customize the animation:

  • The value you pass to setAnimationDuration will speed up or slow down the animation.
  • You can also set an animation curve. The default curve is UIViewAnimationCurveEaseInOut which causes the animation to start slowly, get faster in the middle and then slow before the animation is complete. Other curves like UIViewAnimationCurveEaseIn cause the animation to start slowly and then get faster until completion.

Full Source code: https://github.com/boctor/idev-recipes/tree/master/TabBarAnimation

Tweet This!Hacker NewsShare on Facebook

Full Source code: https://github.com/boctor/idev-recipes/tree/master/RaisedCenterTabBar

Problem:

Apps like Instagram, DailyBooth and Path™ have what looks like a standard UITabBarController, but the center tab bar is raised or colored. How do we recreate this look?


Solution:

These tab bars look pretty standard with the exception of the center item, so we’ll start out with a standard UITabBarController which contains a UITabBar.

Looking at the images inside each app, it is quickly apparent that the middle tab bar is simply a custom UIButton.

A UITabBar contains an array of UITabBarItems, which inherit from UIBarItem. But unlike UIBarButtonItem that also inherits from UIBarItem, there is no API to create a UITabBarItem with a customView.

So instead of trying to create a custom UITabBarItem, we’ll just create a regular one and then put the custom UIButton on top of the UITabBar.

Our basic recipe is then to create a subclass of UITabBarController and add a custom UIButton on top of the UITabBar.

If the button is the same height as the UITabBar, then we set the center of the button to the center of the UITabBar. If the button is slightly higher, then we do the the same thing except we adjust the center’s y value to account for the difference in height.

UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height);
[button setBackgroundImage:buttonImage forState:UIControlStateNormal];
[button setBackgroundImage:highlightImage forState:UIControlStateHighlighted];

CGFloat heightDifference = buttonImage.size.height - self.tabBar.frame.size.height;
if (heightDifference < 0)
  button.center = self.tabBar.center;
else
{
  CGPoint center = self.tabBar.center;
  center.y = center.y - heightDifference/2.0;
  button.center = center;
}

[self.view addSubview:button];

You might notice that in the code we don’t add the button as a subview in viewDidLoad. This is because we have our UITabBarControllers within a UINavigationController. When viewDidLoad is called, our UITabBarController’s view is the entire height of the screen. If we add the button as a subview in viewDidLoad we’d have to manually account for the navigation bar or properly setup the button’s autoresizingMask both of which complicate the code. But after the UITabBarController is pushed onto the UINavigationController stack, the UITabBarController’s view is auto resized to account for the navigation bar. So we delay adding the button as a subview until the UITabBarController’s has been pushed onto the UINavigationController stack. We do this by registering for the navigationController’s willShowViewController callback.

Full Source code: https://github.com/boctor/idev-recipes/tree/master/RaisedCenterTabBar

Tweet This!Hacker NewsShare on Facebook

Full Source code: https://github.com/boctor/idev-recipes/blob/master/CustomSegmentedControls/Classes/CustomSegmentedControlsViewController.m

Problem:

We have an image that we need to crop. Specifically we have a stretchable image but we want to control which cap is visible on the image.

We ran into this when creating custom segmented controls. All we had was a stretchable image with rounded corner caps on both sides and a stretchable 1 pixel in the middle.

But the buttons for a segmented control have either only the left or right cap showing for the end buttons and for the middle button, neither cap is showing.

Solution:

We will use a graphics context to do the image cropping. If you haven’t used contexts before, Apple’s Quartz 2D Overview has a nice description.

To demonstrate, let’s use a stretchable image (‘image’ variable) with 14px caps (‘capWidth’ variable) and let’s generate images 150px wide (‘buttonWidth’ variable).

In all cases we create an image context that is 150px wide and as high as the image:

UIGraphicsBeginImageContextWithOptions(CGSizeMake(buttonWidth, image.size.height), NO, 0.0);

Remember that you can tell stretchable images to draw at any width and they will stretch to accomodate this width.

Left Cap Only

To draw only the left cap, we’ll tell the image to draw at (0,0), but we’ll expand the width enough so the right cap is drawn beyond the bounds of the context.

[image drawInRect:CGRectMake(0, 0, buttonWidth + capWidth, image.size.height)];

We then ask the context to draw itself into an image:

UIImage* resultImage = UIGraphicsGetImageFromCurrentImageContext();

Resulting in this image:

Right Cap Only

To draw only the right cap, we’ll tell the image to draw at (-14,0), and we’ll also expand the width enough so the left cap is drawn beyond the bounds of the context.

[image drawInRect:CGRectMake(0.0-capWidth, 0, buttonWidth + capWidth, image.size.height)];

Resulting in this image:

No Caps

To draw no caps, we’ll tell the image to draw at (-14,0), and we’ll also expand the width enough so that both caps are drawn beyond the bounds of the context.

[image drawInRect:CGRectMake(0.0-capWidth, 0, buttonWidth + (capWidth * 2), image.size.height)]

Resulting in this image:

You can see the full source in the custom segmented controls source: https://github.com/boctor/idev-recipes/blob/master/CustomSegmentedControls/Classes/CustomSegmentedControlsViewController.m

Full Source code: https://github.com/boctor/idev-recipes/tree/master/CustomSegmentedControls

Problem:

UISegmentedControls have only four styles, each with preset heights and colors that you can’t change. How do you create a custom segmented control?

Solution:

The Apple docs say:

A UISegmentedControl object is a horizontal control made of multiple segments, each segment functioning as a discrete button

In other words a UISegmentedControl is simply a group of buttons. To create a custom segmented control we can use a simple recipe:

  • Create a custom view that manages a button for each segment.
  • Use a divider image to visually separate segments.
  • Manage the touches on the buttons so when one is selected, the others are deselected.

We need to also figure out the proper appearance of each button but there are at least two ways to make the images for the buttons:

Instead of having the implementation dictate one way, we’ll use a delegate callback so each instance of the custom control can decide how to build the buttons. The delegate also has optional callbacks to get notified when a touch up or touch down occurs on one of the segments. This will be were we takes actions like swapping out views when a user selects a segment.

CustomSegmentedControl.h

@protocol CustomSegmentedControlDelegate

- (UIButton*) buttonFor:(CustomSegmentedControl*)segmentedControl atIndex:(NSUInteger)segmentIndex;

@optional
- (void) touchUpInsideSegmentIndex:(NSUInteger)segmentIndex;
- (void) touchDownAtSegmentIndex:(NSUInteger)segmentIndex;
@end

@interface CustomSegmentedControl : UIView
{
NSObject <CustomSegmentedControlDelegate> *delegate;
NSMutableArray* buttons;
}

@property (nonatomic, retain) NSMutableArray* buttons;

- (id) initWithSegmentCount:(NSUInteger)segmentCount segmentsize:(CGSize)segmentsize dividerImage:(UIImage*)dividerImage tag:(NSInteger)objectTag delegate:(NSObject <CustomSegmentedControlDelegate>*)customSegmentedControlDelegate;

You can see the full source for CustomSegmentedControl.m as well as a sample app showing the custom control in action: https://github.com/boctor/idev-recipes/tree/master/CustomSegmentedControls

Full Source code: https://github.com/boctor/idev-recipes/tree/master/StretchableImages

Problem:

Images for your iOS apps are too big. You’re creating variations of the same image that only differ in width.

Solution:

A great way to reduce the size of images and reuse images is to use stretchable images.

Smaller image sizes reduce the app size and users will have to wait less for the app to download from the AppStore.

Smaller images also reduce your app’s memory footprint:

Make resource files as small as possible.
Files reside on the disk but must be loaded into memory before they can be used; compress all image files to make them as small as possible.

A stretchable image has 3 parts: A left cap, a one pixel stretchable area and a right cap.
Keith Peters over at Bit-101 has a great image showing this in action:

These images when scaled or resized will draw both caps on either side and repeat the middle pixel.

The most common ways to use stretchable images are:

An entire image stretched by using a 1 pixel wide source image

For example this simple 1 pixel wide image:

UIImage* image = [[UIImage imageNamed:@"1-pixel-image.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:0.0]

If we then use this image in a 300 pixel wide image view:

UIImageView* imageView = [[[UIImageView alloc] initWithImage:image] autorelease];
imageView.frame = CGRectMake(0, 0, 300.0, image.size.height);

we get this image:

An image stretched with equal right and left caps

The source image needs to contain both caps with an extra pixel in the middle. So for example this image is 11 pixels wide, 5 pixels for each cap and a 1 pixel stretchable area in the middle:

UIImage* buttonImage =[[UIImage imageNamed:@"button.png"] stretchableImageWithLeftCapWidth:5.0 topCapHeight:0.0]

results in this image when used in a 300 pixel wide image view:

UIImageView* imageView = [[UIImageView alloc] initWithImage:buttonImage];
imageView.frame = CGRectMake(0, 0, 300.0, buttonImage.size.height);

If we create two images then we can set the background image of a button for the normal and highlighted states and get some very nice looking buttons using very small images.

Here is some sample source code to see stretchable images and buttons in action: https://github.com/boctor/idev-recipes/tree/master/StretchableImages