1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu Lập trình iPhone part 5 ppt

24 301 0
Tài liệu được quét OCR, nội dung có thể không chính xác
Tài liệu đã được kiểm tra trùng lặp

Đ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

Thông tin cơ bản

Tiêu đề Autorotation and Autosizing
Thể loại presentation
Định dạng
Số trang 24
Dung lượng 767,08 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

One example is the mechanism that allows applications to be used in either portrait tall and skinny or landscape short and wide mode and to change that orientation at runtime if the phon

Trang 1

Autorotation

and Autosizing

he iPhone is an amazing piece of engineering Apple engineers found all

kinds of ways to squeeze maximum functionality into a pocket-sized package

One example is the mechanism that allows applications to be used in either

portrait (tall and skinny) or landscape (short and wide) mode and to change

that orientation at runtime if the phone is rotated A prime example of this

behavior, which is called autorotation, can be seen in iPhone’s web browser,

Mobile Safari (see Figure 5-1)

Figure 5-1 Like many iPhone applications, Mobile Safari changes its display based

on howit is held, making the most of the available screen space

Trang 2

Autorotation might not be right for every application Several of Apple’s iPhone applications support only a single orientation Movies can only be watched in landscape mode, for exam- ple, and contacts can only be edited in portrait mode Bottom line, if autorotation enhances the user experience, add it to your application

Fortunately, Apple did a great job of hiding the complexities of autorotation in the iPhone

OS and in the UIKit, so implementing this behavior in your own iPhone applications is actu- ally quite easy

Autorotation is specified in the view controller, so if the user rotates the phone, the view

controller will be asked if it’s OK to rotate to the new orientation (something you'll see how

to do in this chapter) If the view controller responds in the affirmative, the application's window and views will be rotated, and the window and view will get resized to fit the new orientation

A view that starts in portrait mode will be 320 pixels wide and 460 pixels tall or 480 pixels tall if there’s no status bar The status bar is the 20-pixel strip at the top of the screen (see Figure 5-1) that shows things like signal strength, time, and battery charge When the phone

is switched to landscape mode, the view rotates, along with the application's window, and gets resized to fit the new orientation, so that it is 480 pixels wide by 300 pixels tall (320 pixels if there’s no status bar)

Most of the work in actually moving the pixels around the screen is managed by the iPhone

OS Your application’s main job in all this is making sure everything fits nicely and looks

proper in the resized window

Your application can take three general approaches when managing rotation Which one you use depends on the complexity of your interface, and we'll look at all three approaches

in this chapter With simpler interfaces, you can simply specify the correct autosize attri- butes for all of the objects that make up your interface Autosize attributes tell the iPhone

how your controls should behave when their enclosing view gets resized If you’ve worked with Cocoa on Mac OS X, you're already familiar with the basic process, because it is the

same one used to specify how Cocoa controls behave when the user resizes the window in

which they are contained You'll see this concept in action in just a bit

Autosize is quick and easy but not appropriate for all applications More complex interfaces have to handle autorotation in a different manner For more complex views, you have two basic approaches One approach is to manually reposition the objects in your view when notified that your view is rotating The second approach is to actually design two different versions of your view in Interface Builder, one for portrait mode and a separate one for land- scape mode In both cases, you will need to override methods from UIViewControl ler in your view’s controller class

Trang 3

Let's get started, shall we? We'll look at autosizing first

Handling Rotation Using Autosize Attributes

Start a new project in Xcode, and call it Autosize We're going to stick with the same

view-based application template for this application Before we design our view in Interface Builder, we need to tell the iPhone that our view supports autorotation We do that by modify- ing the view controller class

Specifying Rotation Support

Once your project is open in Xcode, expand the Classes folder, and single-click

AutoSizeViewController.m lf you look at the code that’s already there, you'll see that

a method called shoul dAutorotateToInterfaceOrientation: is already provided for you courtesy of the template The method should look like this right now:

- (BOOL) shouldAutorotateToInterfaceOrientation:=>

(UIInterfaceOrientation)interfaceOrientation {

// Return YES for supported orientations

return CinterfaceOrientation == UIInterfaceOrientationPortrait);

This method is the system's way of asking your view controller if it’s OK to rotate to a specific

orientation There are four defined orientations that correspond to the four general ways that the iPhone can be held:

Trang 4

LP

Have you noticed that the defined system constants on iPhone are always designed so that values that

work together start with the same letters? One reason why UIInterfaceOrientationPortrait,

UIInterfaceOri entati onPortraitUpsi deDown, UIInterfaceOri entationLandscapeLeft

and UI InterfaceOrientationLandscapeRight all begin withUIInterfaceOrientation

is to let you take advantage of Xcode’s Code Sense feature You've probably noticed that when you type in Xcode, it often attempts to complete words that you type That’s Code Sense in action Developers cannot possibly remember all the various defined constants in the system, but you can remember the common

beginning for the groups you use frequently When you need to specify an orientation, simply type

UlinterfaceOrientation (or even Ulinterf) and then press the escape key to bring up a list of all matches (in

Xcode’s preferences, you can change the key that’s used) All of the valid constants, variables, methods, and

functions that match what you've typed so far will pop up so you can select them by pressing the tab or

return key This is much faster than having to go look the values up in the documentation or header files

The default implementation of this method looks at interfaceOrientation and only

returns YES if it is equal to UIInterfaceOrientationPortrait, which basically limits this application to one orientation, effectively disabling autorotation

If we wanted to enable rotation to any orientation, we'd simply change the method to return

YES for any value passed in, like so:

- (BOOL) shouldAutorotateToInterfaceOrientation:

(UIInterfaceOrientation)interfaceOrientation {

return YES;

In order to support some but not all orientations, we have to look at the value of

interfaceOrientation and return YES for those that we wish to support and NO for those

we don't For example, to support portrait mode and landscape mode in both directions but not rotation to the upside down portrait mode, we could do this:

Go ahead and change the shoul dAutorotateToInterfaceOrientation: method to match

the preceding version As a general rule, UIInterfaceOrientationPortraitUpsideDown

is discouraged by Apple, because if the phone rings while it is being held upside down, the phone is likely to remain upside down when it’s answered

Trang 5

Save, and then we'll look at setting autosize attributes in Interface Builder

Designing an Interface with Autosize Attributes

In Xcode, expand the Resources folder, and double-click 8 >-T——T_.zccvc— _.-x-ys=rsaan AutoSizeViewController.xib to open the file in Interface

Builder One nice thing about using autosize attributes is

that they require very little code We do have to specify

which orientations we support, as we just did in our view

controller, but everything else we need to do in order to

implement this technique will be done right here in Inter-

face Builder

To see how this works, drag six Round Rect Buttons from the

library over to your view, and place them as we've done in

Figure 5-2 Double-click each button, and assign a title to

each one, so we can tell them apart later We’ve numbered

Figure 5-2 Adding six numbered

Save, and go back to Xcode Let's see what happens now

buttons to the interface

that we've specified that we support autorotation but

haven't set any autosize attributes Build and run Once the iPhone simulator comes up, select Rotate Left from the Hardware menu, which will simulate turning the iPhone into

landscape mode Take a look at Figure 5-3 Oh, dear

Figure 5-3 Well, that’s not very useful, is it?

Most controls default to a setting that has them stay where they are in relation to the left side and top of the screen There are some controls for which this would be appropriate The top left button, number 1, for example, is probably right where we want it—the rest of them, however, not so much

Quit the simulator, and go back to Interface Builder

Trang 6

Figure 5-4 The size inspector allows

you to set an objectS autosize attributes

The size inspector allows you to set an object’s autosize attributes Figure 5-5 shows the part of the size inspector that controls an object's autosize attributes

The box on the left in Figure 5-5 is where we actually set the attributes; the box on the right

is a little animation that will show us how the object will behave during a resize In the box

on the left, the inner square represents the current object If a button is selected, the inner square represents that button

The red arrows inside the inner square represent the horizontal and vertical space inside the selected object Clicking either arrow will change it from solid to dashed or from dashed back

to solid If the horizontal arrow is solid, the width of the object is free to change as the window resizes; if the horizontal arrow is dashed, the iPhone will try to keep the width of the object at its original value if possible The same is true for the height of the object and the vertical arrow

Trang 7

The four red “I” shapes outside the inner box represent the distance between the edge of the

selected object and the same edge of the view that contains it If the “I” is dashed, the space

is flexible, and if it’s solid red, the amount of space should be kept constant if possible Huh?

Perhaps this will make a little more sense if you actually

see it in action Take a look back at Figure 5-5, which repre-

sents the default autosize settings These default settings

specify that the object’s size will remain constant as its

superview is resized and that the distance from the left

and top edges should also stay constant If you look at the

animation next to the autosize control, you can see how it

will behave during a resize Notice that the inner box stays

in the same place relative to the left and top edges of the

parent view as the parent view changes in size

“| „

Try this experiment Click both of the solid red “I” shapes

(to the top and left of the inner box) so they become

dashed and look like the ones shown in Figure 5-6

With all the lines set to dashed, the size of the object will

be kept the same, and it will float in the middle of the

superview as the superview is resized

Now, click the vertical arrow inside the box and the “I”

shape both above and below the box so that your auto-

size attributes look like the ones shown in Figure 5-7

With this configuration, we are indicating that the verti-

cal size of our object can change and that the distance

from the top of our object to the top of the window and

Autosizing

I

of the size inspector

Autosizing

the distance from the bottom of our object to the bottom of the window should stay con-

stant With this configuration, the width of the object wouldn't change, but its height would Change the autosize attributes a few more times and watch the animation until you grok how different settings will impact the behavior when the view is rotated and resized.

Trang 8

Setting the Buttons’ Autosize Attributes

Now, let’s set the autosize attributes for our six buttons Go ahead and see if you can figure

them out If you get stumped, take a look at Figure 5-8, which shows you the autosize attri- butes needed for each button in order to keep them on the screen when the phone is rotated

Figure 5-8 Autosize attributes for all six buttons

Once you have the attributes set the same as Figure 5-8, save the nib, go back to Xcode, and build and run This time, when the iPhone simulator comes up, you should be able to select

Rotate Left or Rotate Right from the Hardware menu and have all the buttons stay on the

screen (see Figure 5-9) If you rotate back, they should return to their original position This technique will work for a great many applications

In this example, we kept our buttons the same size, so now all of our buttons are visible and usable, but there is an awful lot of unused white space on the screen Perhaps it would be better if we allowed the width or height of our buttons to change so that there will be less empty space on the interface? Feel free to experiment with the autosize attributes of these six buttons, and add some other buttons if you want Play around until you feel comfortable

with the way autosize works

In the course of your experimentation, you’re bound to notice that, sometimes, no combina-

tion of autosize attributes will give you exactly what you want Sometimes, you are going to

need to rearrange your interface more drastically than can be handled with this technique For those situations, a little more code is in order Let's take a look at that, shall we?

Trang 9

Figure 5-9 The buttons in their new positions after rotating

Restructuring a View When Rotated

In Interface Builder, single-click each of the buttons, and use the size inspector to change the

w and h field to 125, which will set the width and height of the button to 125 pixels When you are done, rearrange your buttons using the blue guide lines so that your view looks like Figure 5-10

Trang 10

Can you guess what's going to happen this time when we rotate the screen? Well, assuming

that you returned the buttons’ autosize attributes back to those shown in Figure 5-8, what

will happen isn’t likely what we want to happen The buttons are going to overlap and look like Figure 5-11, because there simply isn’t enough height on the screen in landscape mode

to accommodate three buttons that are 125 pixels tall

Figure 5-11 Not exactly what we want

We could accommodate this scenario using the autosize attributes by allowing the height

of the buttons to change, but that’s not going to make the best use of our screen real estate because it’s going to leave a large white gap in the middle If there was room for six square buttons when the interface was in portrait mode, there should still be room for six square

buttons in landscape mode, we just need to shuffle them around a bit One way we can

handle this is to specify new positions for each of the buttons when the view is rotated Declaring and Connecting Outlets

To change a control's attributes, we need an outlet that points to the object we want

to change As a result, we need to declare an outlet for each of the six buttons in order to rearrange them Add the following code to AutosizeViewController.h:

#import <UIKit/UIKit.h>

TBOutTet UIButton *button]l;

TBOutTet UIButton *button2;

TBOutTet UIButton *button3;

TBOutTet UIButton *button4;

TBOutTet UIButton *button5;

TBOutTet UIButton *button6;

}

@property (nonatomic, retain) UIView *buttonl;

@property (nonatomic, retain) UIView *button2;

@property (nonatomic, retain) UIView *button3;

@property (nonatomic, retain) UIView *button4;

Trang 11

@property (nonatomic, retain) UIView *button5;

@property (nonatomic, retain) UIView *button6;

@end

Save this file, and go back to Interface Builder Control-drag from the File’s Owner icon to each of the six buttons, and connect them to the corresponding outlet Once you've con-

nected all six, save the nib, and pop back over to Xcode

Moving the Buttons on Rotation

To move these buttons to make the best use of space, we need to override the method

wi 1 1AnimateSecondHal fOfRotationFromInterfaceOrientation:duration: in

AutosizeViewController.m This method gets called automatically after a rotation has

occurred but before the final rotation animations have occurred

OTE

Another method called wi 1 |AnimateFirstHalfOfRotationToInterfaceOrientation: duration: is available for use, and we'll use it later in this chapter Changes made in that method will finish before the rotation animation does, and the method is designed for making changes that should happen before the rotation animation is completely done In our case, we want the buttons to finish mov- ing to their new positions at the same time the rotation finishes, which is why we chose the second-half method

Add the following code, and then we'll talk about what it’s doing:

Trang 12

button1 frame = CGRectMake(20, 20, 125, 125);

button2 frame = CGRectMake(175, 20, 125, 125);

button3 frame = CGRectMake(20, 168, 125, 125);

button4 frame = CGRectMake(175, 168, 125, 125);

button5 frame = CGRectMake(20, 315, 125, 125);

button6 frame = CGRectMake(175, 315, 125, 125);

else

buttonl frame = CGRectMake(20, 20, 125, 125);

button2 frame = CGRectMake(20, 155, 125, 125);

button3.frame = CGRectMake(177, 20, 125, 125);

button4 frame = CGRectMake(177, 155, 125, 125);

button5 frame = CGRectMake(328, 20, 125, 125);

button6 frame = CGRectMake(328, 155, 125, 125);

// Releases the view if it doesn't have a superview

// Release anything that's not essential, such as cached data

The size and position of all views, including controls like buttons, are specified in a property called frame, which is a struct of type CGRect CGRectMake is a function provided by Apple that lets you easily create a CGRect by specifying the x and y positions along with the width and height The only potentially confusing thing in this code is the fact that we are notified not of the orientation that we rotated to but the orientation that we rotated from Because

we need to know the new orientation, we ignore that parameter and use the

interfaceOrientation property inherited from UIViewController

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

TỪ KHÓA LIÊN QUAN