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

25 444 0
Tài liệu Lập trình ứng dụng cho iPhone part 4 pdf

Đ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

55 Advanced WebKit and textual web apps In the previous chapter we covered the fundamentals of redeveloping an existing web page for use on iPhones. In the process you learned about important concepts like the viewport, and we discussed a lot of what works—and what doesn’t—on Apple’s unique mobile platform. We expect, though, that most of you aren’t just interested in touching up existing web pages but instead are looking to create totally new programs. Further, after considering the advantages and disadvantages of both web and native development, you’ve decided that writing a new program using a web language is the best way to go. We’re now ready to enter the world of web apps, a topic that will consume the rest of part 2 of this book. We’ve identified three ways to create web apps for the iPhone. Each will take advantage of all your existing web knowledge, but each will also connect you with a specific library or Apple browser add-on that will allow you to unlock additional functionality on the iPhone platform. This chapter covers ■ Learning about the WebKit ■ Recognizing touch gestures ■ Recognizing orientation 56 CHAPTER 4 Advanced WebKit and textual web apps First, you might choose to build a textual web app, which is an application that is largely built on the fundamentals of HTML itself. You’ll be able to supplement it with the advanced features of Apple’s WebKit. We’ll be discussing this programming method in this chapter. Second, you might choose to build an iPhone- UI web app, which is an application with a user interface that looks like iPhone’s native apps. That will be the topic of chap- ter 5, where we’ll also cover i UI, a programming library meant to make this task easier. Third, you might choose to build a graphical web app, which is an application that pushes the boundaries of web graphics. That will be the topic of chapter 6, where our discussion will center on Canvas, a graphical add-on introduced by Apple several years ago that is now widely available. Let’s get started with the first of those topics: textual web apps and the advanced functionality of Apple’s WebKit. In this chapter we’ll explore a wide variety of WebKit options, starting with simple HTML and CSS, and then build on that with advanced functionality such as transformations and databases. We’ll conclude with some code that’s iPhone only. 4.1 Introducing the WebKit We touched on the WebKit in the previous chapter when we talked about the iPhone’s viewport command. As we noted there, the WebKit is a browser engine that underlies several existing browsers. It was originally derived from the Linux browser Konquerer, and is now in wider use on Unix-derived systems. It’s Apple who has brought the WebKit to the greatest prominence to date, and thus it should be no surprise that it’s Apple who is pushing hardest on new features for the WebKit. It’s those new features that should excite you as iPhone developers, because they represent totally new functionality that you can use on the iPhone and that isn’t yet available on Internet Explorer or Firefox. You’ll innately be making your web apps incompatible with those browsers if you start depending heavily on WebKit tricks, but we figure that’s the point: using all the tricks you can to produce the best possible web apps for use largely or exclusively by the iPhone. As you’ll recall from chapter 3, there’s some information on the WebKit at Apple’s Web Apps site. As of this writing, it’s pretty rudimentary, but we suspect it’ll improve with time. Even now it has somewhat greater breadth than this chapter, covering some special functions that we don’t get to here. WebKit compatibility note Although we’re highlighting the WebKit for the advanced functionality it offers to the Apple iPhone, you can make greater use of the features in this chapter that are not iPhone specific. This includes new tags, various sorts of animation, and the client- side database. Most notably, these features should work on Apple’s desktop Safari, the brand-new Google Android and Google Chrome platforms, and GNOME’s Epiphany browser. Many of these features will become more accessible when they’re accepted into new HTML and CSS standards. 57Introducing the WebKit We’ll offer the warning that all of this functionality is very new. Since some of the functions are being offered for future HTML and CSS standards, they could change entirely. Even now they’re not entirely consistent. Over the course of writing this chap- ter we discovered one minor function (a transitioning rotation) that worked on Safari but not mobile Safari and a whole category of functionality (explicit animation) that worked on mobile Safari, but nowhere else. We expect that by the time this book is published, behavior will be more consistent across versions of Safari, but our prime goal has been to document how things will work on the iPhone. 4.1.1 New HTML elements The WebKit introduces several new HTML elements. We’ve listed the ones most likely to be useful for iPhone design in table 4.1. There are also some variants of <pre> and some alternate ways to do embeds and lay- ers, most of which are being deprecated in HTML 4.01. 4.1.2 New CSS elements The bulk of the WebKit’s new functionality comes from its large set of extensions to the CSS standards. These include the full set of transforms, transitions, and anima- tions that we cover separately later in this chapter, as well as some simpler CSS ele- ments that are summarized in table 4.2. Table 4.1 WebKit HTML elements give some new basic features for your iPhone web design. Tag Summary <canvas> WebKit/JavaScript drawing object; discussed in chapter 6 <marquee>content</marquee> Sets content (which could be text or other object) as a horizontally scrolling marquee <meta name="viewport"> Metatag for the iPhone; discussed in chapter 3 Table 4.2 This partial list shows the numerous simple new CSS elements that can be incorporated into your iPhone designs. HTML element CSS properties Summary Background -webkit-background-size Controls the size of the background image. Box -webkit-border-radius -webkit-border-bottom-left-radius -webkit-border-bottom-right-radius -webkit-border-top-left-radius -webkit-border-top-right-radius Sets the rounded corner radiuses of the box, in length units, either one corner at a time or all using one property. Box -webkit-border-image Allows you to set an image as a box border using a somewhat complex syntax, which is explained in Apple’s reference pages. 58 CHAPTER 4 Advanced WebKit and textual web apps Table 4.2 is not a complete listing, nor does it give you all the details you need to use the properties. There are not only other CSS properties, but also new CSS constants that can be applied to existing properties. Our main purpose is to show you the cooler elements that are available among the WebKit’s basic CSS elements, and to encourage you to find out more information at Apple’s WebApps reference site. Figure 4.1 shows how some of the new WebKit CSS properties could be applied to a simple <div> to create an attractive box that features rounded corners and a three-dimensional back shadow. The <div> is simply defined with a new class name, as is typical for CSS: <div class="roundedbox"> The definition of the roundedbox class then includes several standard CSS properties (to set Box -webkit-box-shadow Sets a drop shadow for a box by designat- ing a horizontal offset, a vertical offset, a blur radius, and a color. Link -webkit-tap-highlight-color Overrides the standard highlight when a user taps on a link on an iPhone. Link -webkit-touch-callout Disables the touch-and-hold info box if set to none. Marquee -webkit-marquee-direction Controls the direction of the marquee, which can go forward, left, right, up, reverse, or several other directions. Marquee -webkit-marquee-increment Controls the distance the marquee moves, in length units. Marquee -webkit-marquee-repetition Limits the number of marquee repetitions. Marquee -webkit-marquee-speed Sets marquee speed to fast, normal, or slow. Text -webkit-text-fill-color -webkit-text-stroke-color -webkit-text-stroke-width Together allows you to differentiate between the interior and exterior of text by setting colors for each and by defining the stroke width using a length unit. Text -webkit-text-size-adjust Adds a percentage to increase size of text on the iPhone. Table 4.2 This partial list shows the numerous simple new CSS elements that can be incorporated into your iPhone designs. (continued) HTML element CSS properties Summary Figure 4.1 New WebKit properties on the iPhone make your pages more attractive. 59CSS transforms, transitions, and animations the background-color and so forth), plus the new border-radius and box-shadow properties, which appear for the first time in Apple’s WebKit. The code to create the roundedbox class is shown in listing 4.1. .roundedbox { background-color: #bbbbee; border: 1px solid #000; padding: 10px; -webkit-border-radius: 8px; -webkit-box-shadow: 6px 6px 5px #333333; } All of the other new CSS properties could be used in a similar way. THE IPHONE-SPECIFIC PROPERTIES Before we finish our discussion of the simpler WebKit CSS properties, we’d like to point out the ones specifically intended for the iPhone. –webkit-tap-highlight- color and –webkit-touch-callout each give you some control over how links work on the iPhone. It’s the last iPhone-specific property, –webkit-text-size-adjust , that is of particular note, because it allows you to increase point size by a percentage only on the iPhone. In chapter 3, we talked a bit about adjusting font sizes through multiple CSS files. However, if that’s all you need to do differently between iPhones and desktop brows- ers, you can do it with a single line in your CSS file: body { -webkit-text-size-adjust: 120%; } Having now explored the mass of simple additions that the WebKit offers to iPhone developers, we’re ready to dive more wholeheartedly into the big stuff, starting with a variety of advanced CSS methods that you can use to manipulate and animate the con- tent of your web page. 4.2 CSS transforms, transitions, and animations One of the most innovative elements of the WebKit is its ability to manipulate existing HTML objects in various ways, allowing you to accomplish some fancy-looking work entirely in CSS. You have three options: transformation (or static changes), transitions (or implicit animations), and animations (or explicit animations). 4.2.1 The transform function Transforms allow you to apply various geometric functions to objects in a web page when they’re created. There’s no animation here (yet), but you have considerable control over exactly what your HTML objects look like. Each transform is applied using a –webkit-transform CSS property: -webkit-transform: rotate(30deg); Several transforms are available, as shown in table 4.3. Listing 4.1 Using the new CSS web properties to create an attractive box 60 CHAPTER 4 Advanced WebKit and textual web apps The properties in table 4.3 are applied to boxes within CSS. Much like relative posi- tioning, they don’t affect layout, so you have to be careful with them. The following definition could be added to our roundedbox class from listing 4.1, turning it into a wackybox class: -webkit-transform: rotate(30deg) translate(5%,5%); The result is that your news article appears at an angle, moved somewhat off the screen. Figure 4.2 shows this change, which you can compare to the nontransformed news article that appears a few pages back as figure 4.1. This particular transform isn’t that useful if you want people to read it, but it could be a nice background for a news site or something similar. There are many other things that you can do with transforms, such as setting up banners, printing text at a variety of sizes, and making similar changes on static web pages. Some will be gimmicks, but others can have func- tional benefits. Before we leave transforms behind, we’ll note that they support one other property, –webkit-transform-origin , which can be used to move the origin for scales and skews away from the center of the object. Although you can do quite a bit with transforms all on their own, their real power appears when you start working with the implicit animation of transi- tions, which are the next WebKit func- tion that we’re going to talk about. Table 4.3 The WebKit transforms apply to output elements in a variety of ways. Function Argument Summary scale scaleX scaleY Number Resizes the object rotate CSS angle Rotates the object translate translateX translateY Length (or percentage) in X direction, Length (or percentage) in Y direction Moves the object skew skewX skewY CSS angle Skews the object Figure 4.2 Our roundedbox transformed into a wackybox, which is rotated 30 degrees and translated 5 percent along each of the X and Y axes. 61CSS transforms, transitions, and animations 4.2.2 The transition function A transition is also called an “implicit animation” because it supports animated frames, but you, as a web designer, don’t have to worry about how the animation occurs. All you do is define the endpoints. To define a transition, you place the new –webkit-transition properties in the CSS element that marks the end of your animation. You can define what properties to transition (possibly including all of them), how long the transition should last, and how the transition should work. Then, when the block of text changes to the end- point class, a smooth and animated transition will occur. Table 4.4 lists the various transition properties. Unfortunately, not all CSS properties can be transitioned. Apple states that “any CSS property which accepts values that are numbers, lengths, percentages or colors can be animated.” This isn’t entirely true, because some percentage-based elements such as font-size don’t yet work. If you want to know whether a CSS property can be transi- tioned, you can find a list on the Apple website. And there’s no harm if you list some- thing that doesn’t transition in a property; it just does an abrupt change instead. You can reduce a transition command to a single line of code using the –webkit- transition shorthand property: -webkit-transition: property duration timing-function delay Separate additional transitions after the first with commas. Traditional websites are already making good use of transitions to highlight page elements when a hover occurs. However, hovers aren’t possible on the iPhone, so it’s more likely that you’ll be making transitions based on a click. Listing 4.2 shows a sim- ple transition of a box to color in the text and background (making it more visible) when you click it. div { -webkit-transition: all 2s; } Table 4.4 Transitions let you animate changes of CSS properties. Property Values Summary -webkit-transition- property Various properties, including all Defines the property to animate -webkit-transition- duration Time value, such as 1s Specifies how long the animation takes -webkit-transition- timing-function ease, linear, ease-in, ease-out, ease-in-out, or cubic-bezier (user-defined) Defines the curve for how the ani- mation occurs; ease was auto in previous versions of the iPhone OS -webkit-transition- delay Time value, such as 1s Specifies how long to wait to start transition Listing 4.2 Using transitions to animate changes between styles 62 CHAPTER 4 Advanced WebKit and textual web apps .clearbox { background-color: #bbbbbb; opacity: .5; // Other properties make our box beautiful } .visiblebox { background-color: #bbbbee; opacity: 1; // Other properties make our box beautiful } Once you’ve defined these styles, you just need to add an onclick event handler that shifts from one style to the other: <div class="clearbox" onclick="this.className='visiblebox'"> This simple transition could easily be built into a more sophisticated interface where a user could make individual elements of your page more or less visible by clicking on those individual elements (or alternatively through some pagewide control panel). Seeing this simple example highlights why transitions are called implicit animation. You don’t have to do a thing other than define your endpoint styles and say what you want to animate between them. In this example, your pages enjoy a nice animation from gray to cyan, with increasing opacity, thanks just to your defining two styles (and a transition for all <div> s). However, transitioning between normal styles is just the tip of the iceberg. The coolest thing about transitions is that they can be used with that other new WebKit fea- ture we just discussed: transforms. TRANSITIONING TRANSFORMS By putting together transforms and transitions, you can create actual graphical anima- tions of scales, rotates, skews, and translations. In other words, you can make boxes revolve, move, and otherwise change, showing off sophisticated graphical animations, with nothing but CSS definitions (and perhaps a bit of JavaScript to change the styles). Listing 4.3 shows how to put a transition and a transform together to create an ani- mated thumbnail program. ::thumbnail.css:: div { -webkit-transition: all 14s; } .imagebox { -webkit-transform: scale(.2); } ::thumbnail.html:: <head> <title>Thumbnail Viewer in WebKit</title> <link href="thumbnail.css" type= "text/css" rel="stylesheet"> <meta name="viewport" content = "width = 480"> <script type="application/x-javascript"> Listing 4.3 Scaling a picture to create thumbnails B C 63CSS transforms, transitions, and animations var i = 0; function animatePic(mystyle) { i = (i + 1) % 2; if (i == 1) { mystyle.webkitTransform='scale(1) rotate(360deg)'; } else { mystyle.webkitTransform='scale(.2)'; } } </script> </head> <body> <div id="mydiv" class="imagebox" onclick="animatePic(this.style);"> <img src="cat.jpg"> </div> </body> </head> For the example in listing 4.3, your transforms are enacted in JavaScript. Therefore, your CSS file only needs to do two things. First, you set up all <div> s so that they’ll tran- sition B , and second, you set the initial scale of your images to be .2 C , which means that your images will be read in at full size but then displayed in a much smaller form. Your <div> is then set up to use the imagebox class and call the animatePic func- tion when clicked G . animatePic does all the magic D . Every other click, it either scales up and rotates E or scales back down F , using the webkitTransform property. The rotate animation is just a graphical flourish to make the animation look more attractive. Figure 4.3 shows this simple transition. We’ll also offer a brief aside on that rotate: for the moment the rotate animation works on Safari, but not on mobile Safari, which is why you don’t see the thumbnail twisting in figure 4.3. As we’ve already explained, we expect the platforms will eventu- ally sync, perhaps by the time this book sees print, but we offer this as a further caveat. D E F G Figure 4.3 A thumbnail (left) is animated by a tap (middle), turning it into a full-page picture (right). 64 CHAPTER 4 Advanced WebKit and textual web apps In any case, what’s the end result of our work? As long as you’re on a setup where you don’t mind loading larger pictures, you can thumbnail easily. More importantly, you can see how easy it is to use attractive implicit animations to scale thumbnails on your iPhone by combining the transition and transform properties. 4.2.3 The animation function Transitions support fully featured animations, within the constraints of the CSS prop- erties and the transform abilities. So, how can the WebKit’s “explicit” animation improve on that? The answer is by giving you better control over how the animation works. Listing 4.4 shows an example of animation in use. .imagemove { -webkit-transform: scale(.2); -webkit-animation-name: 'moveit'; -webkit-animation-duration: 5s; -webkit-animation-iteration-count: 1; } @-webkit-keyframes 'moveit' { 0% { left: 0px; top: 0px; } 20% { left: 0px; top: 100px; } 100% { left: 0px; top: 450px; opacity: 0; } } To create an animation, you must define a style B that includes a set of –webkit- animation properties. The three critical ones are –webkit-animation-name C , which is the name for the animation; -webkit-animation-duration D , which is the length of the animation, and –webkit-animation-iteration-count E , which is the number of times to repeat the animation. The animation itself is defined by a @-webkit-keyframes entry F , where the name matches the name you already set. You can define as many frames as you want, setting whatever CSS properties you desire in each frame. Then when the anima- tion occurs, the WebKit will automatically transition among all the individual points. Unlike transitions, an animation will return to its start point when it’s done, possi- bly iterating. Listing 4.4 Using animation keyframes B C D E F [...]... together into events 4. 5.1 Accessing events Based on its standard touch and gesture models, the WebKit recognizes seven Document Object Model (DOM) event classes, as shown in table 4. 7 Table 4. 7 With touches and gestures, you can recognize iPhone touchscreen events Event Summary touchstart A finger touches the iPhone touchmove A finger moves across the iPhone touchend A finger leaves the iPhone touchcancel... have over the iPhone s chrome; now let’s move on to the next iPhone- specific topic: touches and gestures 4. 5 Recognizing touches and gestures In the previous chapter we introduced some rudimentary ways to access events on the iPhone We showed you how to correlate iPhone- initiated touches with regular JavaScript events such as mouseup and mousedown However, now that you’re diving 70 CHAPTER 4 Advanced... shown in figure 4. 4, which as you can see make good use of some of the WebKit CSS elements that we highlighted earlier, showing off the great functionality that the WebKit provides you with The JavaScript database is the last WebKit element that you can make use of on the iPhone, but it can also be used more broadly The last couple of items that we’ll discuss are instead iPhone specific 4. 4 Adjusting the... most important Figure 4. 5 Ready for thing to remember when monitoring touch events touchdown! Four boxes set the scene for color dragging through the WebKit 74 CHAPTER 4 Advanced WebKit and textual web apps Unfortunately, unlike with the SDK, there isn’t yet a sophisticated manner to measure which object contains a particular touch; we hope to see that in future releases 4. 5 .4 Accessing gestures Having... you when a user has rotated the iPhone after your web page has loaded Besides just notifying you that an orientation change has occurred, the iPhone maintains a special orientation property in the window object that advises you of the iPhone s current orientation, as described in table 4. 11 Table 4. 11 window.orientation always reflects the current orientation of an iPhone device Description window.orientation... information on new and upcoming WebKit features) 4. 7.1 CSS gradients CSS gradients will give you the opportunity to embed blended colors on your web page This feature should be particularly useful on the iPhone, since gradients are already a part of the look and feel of iPhone home page icons, and will make individual programs feel more like native iPhone programs The Surfin’ Safari WebKit blog states... gesture, rather than you having to figure it out yourself 4. 6 Recognizing orientation The iPhone supports two different types of gestures Touching the screen is what more immediately comes to mind when you think about user input, but moving the iPhone around—as measured by the accelerometers—is another way in which users can manipulate their iPhone If you need precise accelerometer data, you’ll have... some simple methods for dealing with the iPhone chrome We explained how to scroll the URL bar and noted that the status bar and the bottom bar could not be changed Using the WebKit, you have slightly more control over things, provided that your user is using iPhone OS 2.1 or higher All you need to do is enter a new metatag on your web app’s home page: Figure 4. 4 Data retrieved from a database can then... database is quite simple—presuming you already know SQL Thus the question becomes: how can you use it? 4. 3.3 A sample database A client-side database will have any number of advantages, all of which you can make use of on the iPhone However, there’s one iPhone- specific trick you should consider: iPhones uniquely might be connected to either a fast network (wireless) or a slow network (EDGE or 3G) So... discussed in chapter 14 We’ll see Apple programming patterns and methods two more times in the web part of the book: in chapter 6, when we look at Apple’s Canvas library, and in chapter 7, when we investigate their Dashcode developmental platform 4. 8 Summary The WebKit represents some of the quickest changing technology available for web development on any platform It’s the basis for the iPhone s Safari, . for the iPhone; discussed in chapter 3 Table 4. 2 This partial list shows the numerous simple new CSS elements that can be incorporated into your iPhone. of text on the iPhone. Table 4. 2 This partial list shows the numerous simple new CSS elements that can be incorporated into your iPhone designs. (continued) HTML

Ngày đăng: 21/01/2014, 23:20

Từ khóa liên quan

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

Tài liệu liên quan