iOS Recipe_Tips and Tricks for Awesome iPhone and iPad Apps

  • Published on
    27-Mar-2015

  • View
    4.857

  • Download
    9

Transcript

<p>Prepared exclusively for Mary Smithson</p> <p>Beta BookAgile publishing for agile developers</p> <p>Under Construction The book youre reading is still under development. As part of our Beta book program, were releasing this copy well before a normal book would be released. That way youre able to get this content a couple of months before its available in nished form, and well get feedback to make the book even better. The idea is that everyone wins! Be warned. The book has not had a full technical edit, so it will contain errors. It has not been copyedited, so it will be full of typos and other weirdness. And theres been no effort spent doing layout, so youll nd bad page breaks, over-long lines with little black rectangles, incorrect hyphenations, and all the other ugly things that you wouldnt expect to see in a nished book. We cant be held liable if you use this book to try to create a spiffy application and you somehow end up with a strangely shaped farm implement instead. Despite all this, we think youll enjoy it! Download Updates Throughout this process youll be able to download updated ebooks from your account on http://pragprog.com. When the book is nally ready, youll get the nal version (and subsequent updates) from the same address. Send us your feedback In the meantime, wed appreciate you sending us your feedback on this book at http://pragprog.com/titles/cdirec/errata, or by using the links at the bottom of each page. Thank you for being part of the Pragmatic community! Dave &amp; Andy</p> <p>Prepared exclusively for Mary Smithson</p> <p>downloded from: iDATA.ws</p> <p>iOS RecipesTips and Tricks for Awesome iPhone and iPad AppsMatt Drance Paul Warren</p> <p>The Pragmatic BookshelfRaleigh, North Carolina Dallas, Texas</p> <p>Prepared exclusively for Mary Smithson</p> <p>downloded from: iDATA.ws</p> <p>Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf and the linking g device are trademarks of The Pragmatic Programmers, LLC. Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein. Our Pragmatic courses, workshops, and other products can help you and your team create better software and have more fun. For more information, as well as the latest Pragmatic titles, please visit us at http://www.pragprog.com.</p> <p>Copyright 2011 Pragmatic Programmers, LLC. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. Printed in the United States of America. ISBN-10: 1-934356-74-3 ISBN-13: 978-1-934356-74-6 Printed on acid-free paper. B1.0 printing, March 9, 2011 Version: 2011-3-10</p> <p>Prepared exclusively for Mary Smithson</p> <p>downloded from: iDATA.ws</p> <p>Contents1 Introduction 7</p> <p>Part IBasic UI Recipes1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. Add a Basic Splash Screen Transition . . . Stylize Your Splash Screen Transition . . . Animate a Custom Notication View . . . . Create Reusable Toggle Buttons . . . . . . Form Rounded Views With Textured Colors Put Together a Reusable Web View . . . . . Customize Sliders and Progress Views . . . Shape a Custom Gesture Recognizer . . . . Create Self-Contained Alert Views . . . . . Make a Label for Attributed Strings . . . . . Scroll an Innite Wall of Album Art . . . . . Play Tracks from a Wall of Album Art . . . Have Fun with Auto-Scrolling Text Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .</p> <p>1113 18 24 29 33 37 41 44 49 55 60 66 73</p> <p>Part IITable and Scroll View Recipes14. 15. 16. 17. 18. 19. 20. 21. Locate Table Cell Subviews . . . . . . . Simplify Table Cell Production . . . . . Use Smart Table Cells in a Nib . . . . . Organize Complex Table Views . . . . . Produce Two-Tone Table Views . . . . . Add Border Shadows for Table Views . . Stationary Content in a Zoomable Scroll Build a Carousel Paging Scroll View . . . . . . . . . . . . . . . . . . . . . . . . . . View . . . . . . . . . . . . . . . . . . . . . . . . . . . .</p> <p>7779 82 86 91 97 98 99 104</p> <p>Part IIIGraphics Recipes</p> <p>109</p> <p>Prepared exclusively for Mary Smithson</p> <p>downloded from: iDATA.ws</p> <p>CONTENTS</p> <p>6</p> <p>22</p> <p>Graphics Recipes 22. Draw Gradient Filled Bezier Paths . . . . . . . . . 23. Create Dynamic Images With Multiple Animations 24. Composite and Transform Views . . . . . . . . . . 25. Animate a Gradient Layer . . . . . . . . . . . . . . 26. Reshape Shadows . . . . . . . . . . . . . . . . . . . 27. Display Animated Views . . . . . . . . . . . . . . . 28. Construct a Simple Emitter . . . . . . . . . . . . . 29. Curl the Page to a New View . . . . . . . . . . . . .</p> <p>. . . . . . . .</p> <p>110 112 118 121 125 129 132 136 141</p> <p>Part IVNetworking Recipes30. 31. 32. 33. Tame the Network Activity Indicator Simplify Web Service Connections . Format a Simple HTTP POST . . . . Upload Files Over HTTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .</p> <p>148150 153 157 162</p> <p>Part VRuntime and Debugging Recipes34. 35. 36. 37. 38. 39. Index Leverage Modern Objective-C Class Design Produce Intelligent Debug Output . . . . . Design Smarter User Defaults Access . . . Scan and Traverse View Hierarchies . . . . Initialize a Basic Data Model . . . . . . . . . Store Data in a Category . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .</p> <p>170172 176 180 184 185 186 190</p> <p>Prepared exclusively for Mary Smithson</p> <p>downloded from: iDATA.ws</p> <p>Report erratum this copy is (B1.0 printing, March 9, 2011)</p> <p>Chapter 1</p> <p>IntroductionOur goal as programmers is to solve problems. Sometimes the problems are hard, sometimes theyre easy, and sometimes theyre even fun. Maybe theyre not even problems in the colloquial sense of the word, but we are there to solve them. Our goal as authors is to help you solve your problems better and more quickly than beforepreferably in that order. A recipe book is unique in that the authors choose a specic set of tasks and problems and attack them explicitly, rather than educate at a high, conceptual level. Thats not to say a recipe book shouldnt educate. The blessing of a recipe book comes with trust: you are looking for trustworthy solutions to problems that you dont feel like discovering on your own. The curse of a recipe book, if you allow it, is that you copy and paste the solutions without taking the time to understand them. Its always great to save time by writing less code. But its just as great to think and learn about how you saved that time, and how you can save more of it moving forward. We developed the recipes in this book with these ideas in mind. The recipes show you how to get from start to nish, of course, but we hope they also encourage you to think about when and why to choose a certain path: there are often multiple options, especially in an environment like Cocoa. Many of these recipes were also written for maximum reusability. We werent just satised demonstrating a technique, or a snippet of code that got the job done; we wanted to build solutions that were ready for integration into projects of any kind. Some recipes were born from existing projects, and others will nd their way into new ones with zero</p> <p>Prepared exclusively for Mary Smithson</p> <p>downloded from: iDATA.ws</p> <p>C HAPTER 1. I NTRODUCTION</p> <p>8</p> <p>changes. Weve learned a lot during the process of writing this book, as we do during any project. We certainly hope youll learn something by reading it. Cocoa is a rather opinionated framework, and so opinions on approach are both common and passionate in the Mac and iOS communities. In the interest of consistency, we made some decisions early on about certain patterns and approaches to use in this book. The techniques you see may be familiar to you; they may be employed in a way you hadnt considered; or you may simply have never seen them before. Regardless, wed like to explain some of them up front so that there are no surprises.</p> <p>Formatting and SyntaxA number of code snippets in this book are specially formatted to t the page. A verbose language like Objective-C doesnt always play nicely with character limits, so some of the code may sometimes look unusual. You may encounter terse method or variable names, a seemingly excessive number of temporary variables, and odd carriage returns. Weve tried to preserve the spirit of Cocoa convention as much as possible, but in a few places the printed page won. Dont be alarmed if the coding style suddenly changes from time to time.</p> <p>CategoriesA fair number of recipes make use of categories on standard Apple classes to accomplish tasks. Categories are an incredibly powerful feature of the Objective-C programming language, and they tend to alienate new Cocoa programmers. They arent to be feared, but they are to be respected. Categories can quickly pollute namespaces and create (or mask) unexpected behavior in complex class hierarchies. When considering a category: 1. Ask yourself if a subclass, or a brand-new class, would be more appropriate. As The Objective-C Programming Language from Apple states: A category is not a substitute for a subclass. 2. Always prex category methods when extending a class you dont control (for example, UIApplication), to avoid symbol collisions with future APIs.</p> <p>Prepared exclusively for Mary Smithson</p> <p>downloded from: iDATA.ws</p> <p>Report erratum this copy is (B1.0 printing, March 9, 2011)</p> <p>C HAPTER 1. I NTRODUCTION</p> <p>9</p> <p>3. Never override dened methods such as -drawRect: in a category. Doing so breaks the inheritance tree by masking the source class implementation.</p> <p>Synthesized Instance VariablesYoull nd few, if any, instance variable (ivar) declarations in the header les and examples that accompany this book. Weve chosen to exclusively use Objective-C 2.0 properties, with the modern runtimes ivar synthesis feature, for declaring class storage. The result is less typing and less reading, so we can concentrate on the recipe itself.</p> <p>Private Class ExtensionsPrivate class extensions are another relatively new feature of ObjectiveC, and theyre frequently used in this book. Private extensions increase readability by minimizing header noise, and they also paint a much clearer picture for adopters or maintainers of your code. The Leveraging Modern Objective-C Class Design recipe introduces both private class extensions and synthesized instance variables for those unfamiliar with either technique.</p> <p>Cleanup in -deallocIn addition to releasing all relevant instance variables in the -dealloc, our examples set them to nil. This practice is one of the most hotly debated topics among Cocoa programmers, and both sides of the argument hold weight. This book is not meant to participate in the debate at all: we set them to nil, but that doesnt mean you have to. If you dont like nil-in-dealloc, feel free to leave it out of your own code.</p> <p>Blocks vs. DelegationBlocks are a new feature added to C and Objective-C in Mac OS X Snow Leopard and iOS 4.0. Due to the relative youth of this feature, the debate on when to use blocks or delegates remains heated. This book uses both at what we felt were appropriate times. Youre more than welcome to add blocks to a recipe that uses delegates, or vice versa. Our goal is ultimately to help you nd the simplest and most natural solutions you can.</p> <p>Prepared exclusively for Mary Smithson</p> <p>downloded from: iDATA.ws</p> <p>Report erratum this copy is (B1.0 printing, March 9, 2011)</p> <p>C HAPTER 1. I NTRODUCTION</p> <p>10</p> <p>Above all, this book is about reducing complexity and repetition in your code. We shouldnt be satised with just solving a problem as soon as possible: we want the solution readily available for the long run. We hope you agree, and that the ideas in these pages aid you in your journey as an iOS developer.</p> <p>Prepared exclusively for Mary Smithson</p> <p>downloded from: iDATA.ws</p> <p>Report erratum this copy is (B1.0 printing, March 9, 2011)</p> <p>Part I</p> <p>Basic UI Recipes</p> <p>Prepared exclusively for Mary Smithson</p> <p>downloded from: iDATA.ws</p> <p>Basic UI RecipesIt wouldnt be hard to write an entire book on UI recipes: the iOS SDK has a seemingly endless library of classes and patterns worth discussing. We ultimately focused on some simple patterns and problems, seeking good solutions. The kinds of things you nd yourself doing over and over again without quite remembering how you did it last time. This section has recipes on view transitions, web content, touch handling, and even custom controls. The recipes are ready to use, and will hopefully inspire you to think about making your own code ready for reuse in the next inevitable project.</p> <p>Prepared exclusively for Mary Smithson</p> <p>downloded from: iDATA.ws</p> <p>Recipe 1</p> <p>Add a Basic Splash Screen TransitionProblem</p> <p>You want the transition from your apps startup image to your initial UI to be as smooth as possible, but youre not sure how to go about this in the cleanest way.Solution</p> <p>The visual experience of an iOS app launching goes something like this: 1. User taps an app icon. 2. Apps default image scales onto the screen. 3. Apps initial UI is loaded into memory. 4. App UI appears on screen, immediately replacing the default image. Whether our Default.png image is a branded banner or a stripped-down screenshot of our core user interface, a harsh transition from the default image to the live UI creates a bad rst impression for our users. There are plenty of ways to make this transition smoother, but lets start with a very simple approach that should be usable from just about anywhere. The simplest possible splash screen transition is a fade between the default image and our UI. Its cheap and easy, and makes a world of difference for our user experience. Think about it: this is the very rst thing our users are going to see. Theres no reason for this introduction to be anything but smooth. In order to fade the default image off screen, we need to show a view that displays the same image, and then fade that view. This is pretty easy to do, but were going to make it even easier through a simple view controller thats usable from any project written for iOS 3.0 and later. This view controller takes a custom splash image and denes a -performTransition method, where well execute the fade.</p> <p>Prepared exclusively for Mary Smithson</p> <p>downloded from: iDATA.ws</p> <p>1. A DD A B ASIC S PLASH S CREEN T R...</p>