Tài liệu Lập trình ứng dụng cho iPhone part 7 ppt

19 455 0
Tài liệu Lập trình ứng dụng cho iPhone part 7 ppt

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

124 Building web apps with Dashcode Thus far, we’ve talked about a lot of great programming libraries that you can use to create versatile and beautiful web apps for use on the iPhone. The WebKit, i UI, and Canvas each offered different ways to program your web pages. Although we’ve looked at several different libraries, we haven’t concerned our- selves at all with the tools that you use to construct your web apps. You might be building your pages with Emacs or Adobe GoLive. You might be testing them out with Firefox or Opera. A variety of tools could be used for any of these tasks, but in this and the next chapter we’re going to suggest some options that we think are particularly effective. We’ll begin in this chapter with a development environment that allows you to create web pages specifically for the iPhone: Dashcode. We’re going to give you plenty of information on Dashcode here. We’ll start off with an introductory look at the program and its parts. Then we’ll give some specific This chapter covers: ■ Introducing the Dashcode development environment ■ Programming simple iPhone web apps with Dashcode ■ Integrating Dashcode with existing libraries 125An introduction to Dashcode advice on using several of the objects and templates that Dashcode provides. Finally, we’ll examine how Dashcode interrelates with the libraries that you’ve worked with over the course of the last three chapters. TIP Some good documentation about Dashcode is available at http:// developer.apple.com/webapps/. If you want more information than we’ve presented in this chapter, read the “Dashcode User Guide.” Let’s get started with a look at where Dashcode came from. 7.1 An introduction to Dashcode Dashcode is a development environment that was introduced by Apple in 2006. At that time, it only allowed for the creation of dashboard widgets, which are simple web applications built using HTML, CSS, and JavaScript that run under Mac OS X without a browser. Apple’s clock, calendar, and calculator are among the applications that have been built using Dashcode. Apple released Dashcode 2.0 in 2008 as part of the large set of development tools for use with the iPhone. Under this new version of Dashcode, you can create web applications intended to run not on a Macintosh but, instead, on an external website for use with an iPhone. Dashcode programs are essentially web pages, so all of your experience with HTML, CSS, and JavaScript will continue to be of use. Much of the HTML and CSS will be hidden by Dashcode’s graphical user interface, but when you want things to hap- pen, you’ll be programming directly in JavaScript. You could theoretically use Dashcode to program web apps of considerable com- plexity, but we suggest using it mainly for simple widgets like those found in the native Mac OS X dashboard. For more complex applications, you’ll want to have access to a more complex language like PHP or Ruby on Rails, and though you could integrate that functionality with Dashcode work, as we’ll explain at the end of this chapter, you’d probably do better to use your standard development environments. Dashcode is really best for small and simple (yet elegant) web apps. At this time, Dashcode 2.0, which is the version that you’ll need to write iPhone web apps, is only available as part of the iPhone SDK. You should thus jump forward to chapter 10 for some information on how to install it. Once you’ve done so, you can run Dashcode from /Developer/Applications/Dashcode. Warning: Mac-specific lands ahead Much of our discussion of developing web pages thus far has not been Macintosh- specific. Clearly, the various libraries will be available no matter what platform you’re writing code on. But starting here we’re going to have a more Apple-centric focus, be- cause tools are more likely to depend on what computer you’re using. 126 CHAPTER 7 Building web apps with Dashcode 7.1.1 Starting a Dashcode project Once you’ve started up Dashcode, you’ll need to begin a project by selecting a tem- plate. Each of these templates comes partially filled in with different starting objects intended to make your development experience quicker and simpler. The various possibilities are summarized in table 7.1. Note that for each template we’ve listed an SDK equivalent template. Apple has used many common techniques for both SDK and Dashcode development, and if you’re transitioning from one to another, these equivalents will help guide you; otherwise, you can ignore them. Generally, you should be able to easily decide which template you want to use based on the needs of your web app. If you’re linking to podcasts or RSS feeds, you’ll use those specific templates. The Utility template should be used whenever you want a simple one-page application with information or preferences of some sort on a sec- ond page, and the Browser template should be used whenever you want to build hier- archies of lists. If none of the templates applies, the Custom template is the right place to start. 7.1.2 The anatomy of Dashcode When you start a Dashcode project, the main screen will display what your project cur- rently looks like, and it’ll also feature a huge variety of buttons and other controls that can be used to build it up. For example, the starting screen for a project based on the RSS template is shown in figure 7.1. The Dashcode screen is broadly divided into three parts. Above is the top bar, which features a few useful buttons. Below and to the right is the canvas. This is area where you can see what your web app looks like. To the left is the navigator, which gives you access to the entirety of your program (and to some helpful advice). There are three additional screens that aren’t initially visible, but which are each quite important: the source code panel, the inspector and the Library. We’ll talk about each of these in turn. Table 7.1 Dashcode templates get you started quickly Template Summary SDK equivalent Browser A navigation controller that is list-based Navigation-based application Custom A totally blank application Window-based application Podcast An application that displays and plays podcasts N/A RSS An application that reads and displays an RSS feed N/A Utility A flipside controller with two screens Utility application 127An introduction to Dashcode ABOUT THE TOP BAR The top bar provides you with buttons to get to a few important pages inside Dash- code. It’s how you call up the inspector and the Library. The View menu lets you replace the canvas and source code panels with some of the subsidiary panels that we’re not going to dig into in this overview. Finally, the Run button lets you test out web apps as you write them. The top bar doesn’t bear much additional discussion, but it’s a great navigational tool inside Dashcode. ABOUT THE CANVAS Dashcode’s development canvas is the right panel of the main page. It’s simple and easy to use. You can manipulate graphical objects there by dragging them around, and the canvas will try to help you keep things aligned by showing clear blue lines when objects align to the middle or edges of the screen. It’ll also sometimes limit where your object can go. For example, if you drag around some of the locations for the arti- cle listings in the existing template, you will see limits on positioning based on Figure 7.1 Dashcode includes a top bar (top) for important buttons, a navigator (left) for getting around your web page, and a canvas (right) to show off your content. 128 CHAPTER 7 Building web apps with Dashcode whether you’re using absolute or document-flow positioning for an individual object. This can be adjusted using the inspector for the object, a topic we’ll return to shortly. Resizing items is equally simple. Besides that, you can also change the textual content of most objects within the canvas. For example, double-clicking on My RSS Feed in the RSS example will allow you to change that title on the page. Just keep in mind that the canvas is a graphical user interface. You can use it to eye- ball the placement of objects in your web app and to make quick and easy changes to the content. ABOUT THE NAVIGATOR The navigator, at the left of the Dashcode screen, contains links to all of the various objects that exist as part of your app. The large blue button (Untitled, in figure 7.1) is where most of those objects are linked in, a topic we’ll return to momentarily. Mean- while, there are a number of additional features in the navigator that we’ll cover first. The Application Attributes button gives you access to some of the big-picture stuff, like your web page’s name and what your app does when an iPhone is rotated. The Home Screen Icon button lets you create a 60x60 web clip for your application, just like you did for your own web pages in chapter 3. You should make sure to do this for any web app you’re writing for the iPhone. Finally, the Share button allows you to deploy your web app. We’ll discuss this in sec- tion 7.1.4. Now let’s return to the blue button at the top of the navigator. If you look, you’ll see that it can be opened to reveal an ever-deepening hierarchy of objects that make up your web page. Three of the first categories that you’ll see are the header (which is a <div> of text that appears across several pages in your web app), the StackLayout (which is an object that contains a listing of all the pages that make up your web app), and the footer (which is a <div> of text that appears at the bottom of your web app). Each of these categories can be opened to reveal additional items. For example, the sample header in the RSS template contains five different objects: a gradient, a title, a date, and two horizontal rules. Clicking on one of these objects will highlight it on the web page and also allow you to easily modify it with the inspector, which we’ll return to shortly. ABOUT THE SOURCE CODE You can access your web app’s source code by calling it up through the View menu in the top bar—this will create a new panel in the bottom right of your main window. Dashcode’s programming is all done in JavaScript, so that’s what you’ll see here. One of the coolest features of Dashcode is that the JavaScript is quite well integrated. As you’ll discover when you’re hooking up buttons, you can hop straight over to the source code, and Dashcode will even fill in some of the details concerning what code you need to write and how. ABOUT THE INSPECTOR You can call up an inspector window by clicking the appropriate button in the top bar. This will open a window that is used to modify specific information for individual objects 129An introduction to Dashcode in Dashcode. For example, the Fill & Stroke inspector is shown in figure 7.2. Here you can manipulate objects more precisely than you can inside the canvas. The inspector window includes five different tabs that can be used to modify a wide variety of settings. Here they are, from left to right: ■ Attributes —Manipulates some of the most basic information about an object, such as the words or images displayed on it. ■ Fill & Stroke —Changes the background color of an object, and how its corners are rounded; also manipulates simple iPhone effects, such as glass and recess. ■ Metrics —Modifies CSS positioning information, such as where an object goes, how big it is, and whether it uses absolute or document-flow posi- tioning; also determines how an object resizes, which can be of relevance when the iPhone’s orientation changes and the size of the objects need to change. ■ Te xt — Changes fonts, colors, spacing, and other text-related settings. ■ Behaviors —Adds event handlers for simple web events and advanced WebKit events, such as the touch and gesture events discussed in chapter 4. The changes you make in the inspector window are largely self-explanatory, but we’ll look at some of them in-depth—particularly the resizing controls and the event handlers—in our examples of Dashcode pro- grams in the next section. ABOUT THE LIBRARY You can call up the Library window by clicking the appropriate button in the top bar. The Dashcode library contains a variety of objects that you can add to your programs, as shown in figure 7.3. The items that you can add to your Dashcode pro- grams are divided into three broad classes: ■ Parts —The Parts Library contains all the objects that you might want to add to your pro- gram, broadly divided into Buttons, Shapes, Containers, Media, and Text. This includes a variety of attractive graphical objects, some of which are styled to match the look and feel of the iPhone. Figure 7.2 The inspector window allows you to modify individual Dashcode objects. Figure 7.3 The Dashcode library gives you access to widgets, code, and your pictures. 130 CHAPTER 7 Building web apps with Dashcode ■ Code —The Code Library features rudimentary code snippets, which primarily remind you how to get and set information for various objects. Many of them show you how to extract information from some of the standard Dashcode objects that you’ll find in the Parts Library, such as the stack layout. If you’re a beginning JavaScript programmer, this will be quite useful; otherwise you will probably only use this tab a few times when you’re learning Dashcode. ■ Photos —This is a built-in interface to iPhoto, giving you quick and simple access to any images in your iPhoto library. All the library sections are easy to use. To add a new object to your project, drag it onto your canvas. Blue lines will help you center your object, if you so desire. After- ward, you can resize the object or otherwise manipulate it using the canvas or the inspector, as appropriate. That concludes our look at the parts of Dashcode. We’ll be putting this all to actual use momentarily, but first we need to talk about what you can do with a Dashcode project when you’re done with it. 7.1.3 Running Dashcode projects At any time, you can test out your current Dashcode project by clicking the green Run button that appears in the top bar. This will run your program inside the iPhone Sim- ulator, a handy iPhone emulator that we’ll discuss more completely in the next chap- ter. Dashcode also gives you access to a sophisticated debugger. If there’s a mistake in your JavaScript code, you’ll get precise information on what went wrong and how. 7.1.4 Deploying Dashcode projects When you’re using Dashcode, you’re creating web pages, complete with HTML and CSS files. In order to make them available for use on iPhones, you need to place them on a web server. This is easy to do. You just click the Share button in the navigator. You’ll have the option to deploy your web app to your local file system. Dashcode will then create a directory containing quite a few files, even for a simple program. The collection of files created for a Dashcode program with just a few but- tons is shown in figure 7.4. We suggest using your local server for testing all programs. We’ll talk more about how to do that in the next chapter, which includes guidelines for running an Apache server on your Mac. Presumably you’ll eventually want to move your Dashcode program over to some larger server, but we’ll leave the specifics of that final deployment to you. Now that you’ve seen the basics of how Dashcode works, you’re ready to dive into some actual programming. 131Writing Dashcode programs 7.2 Writing Dashcode programs Dashcode is ultimately a tool for writing dynamic web pages of light complexity. Not only does it provide you with a great graphical interface, but it also offers you a huge library of complex objects that can each save you hours of programming. But making use of it is largely up to you. Programming with Dashcode requires knowledge of HTML and JavaScript that go beyond the scope of this book. You may wish to consult a book like Secrets of the JavaScript Ninja by John Resig (Manning, 2009) for information on these topics. But to help give you a leg up on using Dashcode, we’ve highlighted four of the most important (or complex) topics that you might encounter: using library parts, adding action buttons, using the list-based Browser template, and working with the stack layout. Figure 7.4 You’ll realize how much work Dashcode does for you when you see all the files it creates, even for a simple program. This terminal window shows just some of the files created. Saving in Dashcode It’s important to remember that there are two ways to output files from Dashcode. First, you can (and should) save your Dashcode project. Do this as soon as you get started, using File > Save. Then, in the Share menu, check the box that says “Save project to disk before deploying” to ensure that your saved Dashcode project always matches your current deployment. Second, you can (and will) deploy your HTML code to a web server when it’s done. It’s easy to forget about the Dashcode project when you’re outputting HTML code. By checking that box in the Share menu, you’ll never have to worry about it, and you’ll be sure that your Dashcode project itself is always up to date. 132 CHAPTER 7 Building web apps with Dashcode 7.2.1 Using library parts In chapter 4, we used the WebKit to create a simple web program that reported the orientation of a user’s iPhone. At the time, we opted to display the information with a textual interface rather than spending the time to put together graphics. Now, with Dashcode at our disposal, we can take advantage of the library parts to display this information graphically with a minimum of work. Table 7.2 shows how to do so, step by step. You should be able to run through this complete proce- dure by following the steps in the table, but the following subsections include some additional information on the more complex steps. The first three steps—creating the project, creating the gauge, and adjusting the gauge—are all pretty simple. Figure 7.5 shows what your miniature gauge will look like; by the time you’re done with this project, the arrow will always point to the top of your iPhone. Table 7.2 We can create a graphical orientation gauge in just a few minutes in Dashcode. Step Description 1. Create a project. Select File > New Project. Choose a Custom project. 2. Create a gauge. Drag a gauge from the Parts library to the top center of your Dashcode canvas. 3. Adjust the gauge. Pop up an inspector window and click on the Attributes tab. In the Values section, change the range to go from 0 to 359, to allow the full range of values. Change the threshold to 0 and warning and critical to 360, to make sure the gauge always remains green. In the Geometry section, change the angles to go from 0 to 359 to match the gauge up with our possible orientation directions. Change the pointer reach to 120% to help it stand out more. 4. Adjust the title and resize. In the main window, click the Application Attributes button in the Navigator sidebar. Change the Title to Orientation Gauge. Change the viewport to Adjust page width to fit, to keep your gauge from resizing. Open the Metrics inspector for the content object. Change resizing so that the left and right springs are outside of the subwindow, rather than inside. 5. Input code. Open a source code panel using the View button. Drag Set Gauge Value from the Code library to the source code panel. Adjust it appropriately to set the gauge’s value on startup and when the orienta- tion changes. 6. Add a home screen icon. Design and input a home screen icon using the Home Screen Icon button in the navigator sidebar. 7. Deploy. Release your new program. Figure 7.5 A simple gauge shows the ease-of-use of the Dashcode parts. 133Writing Dashcode programs You could also look through the inspector window for the gauge to see if there’s anything else that you might want to adjust. The fourth step, where you adjust the resizing, has a few elements that we haven’t previously covered. RESIZING OBJECTS Dashcode supports two models of viewports. The default, which it calls “Zoom pages to fit,” uses a fixed-size viewport (typically 320 pixels wide) and thus causes an iPhone to zoom in when you move from portrait to landscape mode. The other choice, “Adjust page width to fit,” instead sets the viewport to page-width , which means that the page content remains at the same size when an orientation change occurs. The latter results in resizing, which we haven’t talked about much up to now. That’s primarily because it’s a pain to deal with unless you have a program helping you out, like Dashcode (or like Interface Builder, later in this book). When an iPhone changes orientation without zooming, the top-level window implicitly changes size, so the pro- gram then needs to figure out what to do with its subwindows. Do elements like the gauge maintain their position relative to the center of the page, the left, or the right? The top or bottom? Each of these answers might be correct for a different element on a different page. This is what the Autoresize box of the Metrics inspector is for, as shown in figure 7.6. In this case, for the content object’s Autoresize options, you clicked the horizontal springs inside the box to make them go away, and then you clicked new horizontal springs into existence out- side of the box. The result is that when the con- tent object resizes, it keeps the gauge at the middle of the screen. Turning on only one of the right or left springs would have kept it justified in that direction. WRITING THE ORIENTATION CODE As we’ve previously noted, the Code library returns rudimentary code that will show off the basics of how to access many of the Dashcode objects. Here’s what the Set Gauge Value code snippet looks like, with Apple’s original comments: // Values you provide var gaugeToChange = document.getElementById("elementID"); // replace with ID of gauge to change var newGaugeValue = 100; // new gauge value // Gauge code gaugeToChange.object.setValue(newGaugeValue); Once you have that, you just need to place it at an appropriate place in your source code, with appropriate values filled in. Figuring out the ID of the gauge is simple. It’s on the Attributes tab of the inspector. After that, you just need to individualize the code sample to reset the gauge value when orientation changes occur. We already saw Figure 7.6 The Autoresize box tells a window where its subwindows should go when the window’s size changes, usually though an orientation event. [...]... have liked to create a standard iPhone UI tab bar, attached to the bottom of the page, but there weren’t any parts that looked quite right Instead we took advantage of some of the attractive buttons included in the Parts library, as shown in figure 7. 10 In order to mimic this layout, include a left-rounded push button, a push button, and a right-rounded push button You can choose to put these buttons in... all of the parts and code available within Dashcode, but Apple’s already done the job, so we’ll point you one more time toward their “Dashcode User Guide.” At the time of this writing, the user guide’s appendix B contains an excellent list of parts with special functionality To aid your own exploration, table 7. 5 lists some of the most interesting parts that you might want to look up Table 7. 5 Some of... own coding 7. 2.4 Working with the stackLayout part We’re going to finish up our look at Dashcode programs by examining what might be the most complex element of Dashcode: the stackLayout Though the stackLayout is a pretty major building element that will end up controlling multiple views in many of your programs, it’s just another Dashcode part You can find it in the Container section of the Parts library... stackLayout plus any header and footer that you created So, how do you allow users to navigate from one view to another? You use a few methods that come with the stackLayout part They are highlighted in table 7. 4 Table 7. 4 The stackLayout part contains methods that can be used to manipulate the views Method Arguments Summary getAllViews N/A Returns an array of the IDs of all views getCurrentView N/A Returns...134 CHAPTER 7 Building web apps with Dashcode how to look up the orientation value using the WebKit in chapter 4 Listing 7. 1 shows what happens when you put that together with a Dashcode object Listing 7. 1 Automatically setting a gauge based on orientation B function load() { dashcode.setupParts(); var gaugeToChange = document.getElementById("gauge");... represent many similar pages with slightly different content 7. 2.5 Exploring the rest of Dashcode We’ve done our best in this chapter to point out the main features of the Dashcode development environment We’ve shown how to output to parts, how to accept input from them, and how to use two of the most complex parts, the listController and the 140 CHAPTER 7 Building web apps with Dashcode stackLayout We could... thanks to the built-in functionality of Dashcode 7. 2.2 Adding action buttons We’ve just seen how easy it is to output to a Dashcode part It’s equally easy to take input from a Dashcode object As an example, we’ll put together a quick application that includes two lozenge buttons and a horizontal indicator between them This layout is shown in figure 7. 7 Our goal is to make these buttons control the indicator... some great libraries that you can use to create iPhone web apps, and in this chapter we introduced the Dashcode development environment Since these are somewhat orthogonal directions of iPhone development, we want to briefly touch upon how they can be used together We’re going to cover each of the iPhone- related libraries in turn: WebKit, iUI, and Canvas 7. 3.1 Integrating Dashcode with WebKit Apple’s... ways to use web design to create web apps that look like native iPhone apps 7. 3.3 Integrating Dashcode with Canvas Apple’s Canvas graphical extension is the easiest of all the libraries to incorporate into Dashcode You just place a Canvas part from within Dashcode, and then you can write JavaScript code as usual 142 7. 3.4 CHAPTER 7 Building web apps with Dashcode Deeper integration For any Dashcode project,... button Here you’ll see a list of events Figure 7. 7 A few buttons can be easily added through Dashcode Writing Dashcode programs 135 (which includes both standard onclick events and the ongesture events that we met in chapter 4) and handlers To write a new handler, just type the name of a JavaScript function into the Handlers area The result is shown in figure 7. 8 Typing in a handler does two things First, . methods that come with the stackLayout part. They are highlighted in table 7. 4. Table 7. 4 The stackLayout part contains methods that can be used to. as shown in figure 7. 3. The items that you can add to your Dashcode pro- grams are divided into three broad classes: ■ Parts —The Parts Library contains

Ngày đăng: 26/01/2014, 18:20

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan