TTAlertView is a drop-in replacement for UIAlertView that allows the developer to customize the presentation of an alert. TTAlertView uses the familiar interface of UIAlertView, so you don’t have to worry about rewriting any of your code. Just drop it in, add some assets, and bam!: you have a unique, customized alert view for your app!
Using TTAlertView is simple. TTAlertView uses the familiar
show methods to create and display your alert view. From there TTAlertView handles laying out and animating the view.
Lets see some code:
TTAlertView *alert = [[TTAlertView alloc] initWithTitle:@"A Simple TTAlertView"
message:@"... with the default layout!"
… which gives you this:
Of course, this alert hasn’t been customized at all, so it looks lame. Let’s see what adding in some custom images can do for us…
To customize this alert view, we’re going to set the background image for
containerView (the box containing the title, message, and buttons). Since TTAlertView handles the layout and, most importantly, the sizing of the
containerView, using a resizable UIImage here is best practice — this guarantees that no matter the size of the
containerView, the image will be stretched appropriately to fit.
We’re also going to add some button images using TTAlertView’s
setButtonBackgroundImage:forState:atIndex: method. With this method we will set images for the button’s normal and highlighted states, again using resizable UIImages. (If you’re using textured button images or button images with text baked in, worry not – we’ll cover how to use these types of assets in a future blog post!)
Here’s some more code:
TTAlertView *alert = [[TTAlertView alloc] initWithTitle:@"A Fancy TTAlertView"
message:@"... with images and designs!"
// we don't want the background peeking through
[alert.containerView setBackgroundColor:[UIColor clearColor]];
// resizable images work best
UIImage *backgroundImage = [bgImage resizableImageWithCapInsets:bgCapInsets];
UIImage *buttonOffImage = [btnOffImage resizableImageWithCapInsets:buttonCapInsets];
UIImage *buttonOnImage = [btnOnImage resizableImageWithCapInsets:buttonCapInsets];
[alert setButtonBackgroundImage:buttonOffImage forState:UIControlStateNormal atIndex:0];
[alert setButtonBackgroundImage:buttonOnImage forState:UIControlStateHighlighted atIndex:0];
… and voilá!
We’re done here
A quick shout-out to one of our favorite clients: Go Try It On. GTIO provided the assets used in the stylized alert example seen above — the assets were taken from the custom alert view in GTIO’s app, which is where TTAlertView was pioneered!
This is just a taste of TTAlertView’s potential. In future posts we will cover more ways to use TTAlertView, like using fixed-size images, tweaking the layout, and supplying custom view hierarchies. Stay tuned!