天天看點

iPhone開發之UIScrollView初步

iPhone開發之UIScrollView初步

今天我們初步介紹以一下iPhone開發中的UIScrollView。顧名思義,UIScrollView就是可以滾動的視圖,常常用在圖檔顯示(縮放,滾動等),文本顯示等,是一個非常有用的控件。今天我們的例子很簡單:在頂部有一個文本框和一個按鈕,在文本框中輸入數字,點選按鈕,就會在下方的UIScrollView中出現相應數目的按鈕,超出一屏的部分用垂直滾動條顯示。這個例子我們用兩種方法實作。并且我們都不使用Interface Builder來畫界面,完全手工寫代碼完成。下面開始吧:

方法1:

1.

建立一個View-based Application,名稱是Scroll

iPhone開發之UIScrollView初步

2.

修改 ScrollViewController.h 如下:

//  

//  ScrollViewController.h  

//  Scroll  

//  Created by HuTao on 8/21/12.  

//  Copyright __MyCompanyName__ 2012. All rights reserved.  

#import <UIKit/UIKit.h>  

@interface ScrollViewController : UIViewController<UIScrollViewDelegate>  

{  

    UITextField * textFieldNumber;  

    UIButton * btnStart;  

    UIScrollView * scrollView;  

    NSMutableArray * btnArray;  

}  

@property (retain, nonatomic) UITextField * textFieldNumber;  

@property (retain, nonatomic) UIButton * btnStart;  

@property (retain, nonatomic) UIScrollView * scrollView;  

@property (retain, nonatomic) NSMutableArray * btnArray;;  

-(IBAction)btnStartAction:(id)sender;  

-(IBAction)btnAlert:(id)sender;  

@end  

修改 ScrollViewController.m

如下:

//  ScrollViewController.m  

#import "ScrollViewController.h"  

@implementation ScrollViewController  

@synthesize textFieldNumber;  

@synthesize btnStart;  

@synthesize scrollView;  

@synthesize btnArray;  

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.  

- (void)viewDidLoad  

    [super viewDidLoad];  

    self.view.backgroundColor = [UIColor yellowColor];  

    int widthOut = self.view.frame.size.width;  

    int widthIn = widthOut - 20;  

    btnArray = [[NSMutableArray alloc] init];  

    //聲明一個 UITextField  

    textFieldNumber = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, widthIn - 70, 30)];  

    textFieldNumber.backgroundColor = [UIColor whiteColor];  

    textFieldNumber.borderStyle = UITextBorderStyleRoundedRect;  

    [self.view addSubview:textFieldNumber];  

    //聲明一個 UIButton  

    btnStart = [UIButton buttonWithType:UIButtonTypeRoundedRect];  

    [btnStart setTitle:@"開始" forState:UIControlStateNormal];  

    btnStart.frame = CGRectMake(widthIn - 50, 10, 60, 30);  

    [btnStart addTarget:self action:@selector(btnStartAction:) forControlEvents:UIControlEventTouchUpInside];  

    [self.view addSubview:btnStart];  

    //聲明一個 UIScrollView  

    scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 50, widthOut, self.view.frame.size.height - 50)];  

    scrollView.backgroundColor = [UIColor redColor];  

    //任意劃動  

    scrollView.pagingEnabled = NO;  

    //劃動過程中顯示水準滾動條(如果有)  

    scrollView.showsHorizontalScrollIndicator = YES;  

    //劃動過程中顯示垂直滾動條(如果有)  

    scrollView.showsVerticalScrollIndicator = YES;  

    //點選頂部的狀态欄滾動到首  

    scrollView.scrollsToTop = YES;  

    scrollView.delegate = self;  

    [self.view addSubview:scrollView];  

-(IBAction)btnStartAction:(id)sender  

    [textFieldNumber resignFirstResponder];  

    int i;  

    UIButton * button;  

    for(i=0; i<[btnArray count]; ++i)  

    {  

        button = (UIButton *)[btnArray objectAtIndex:i];  

        //先删除所有按鈕(删除後按鈕自然不可見)  

        [button removeFromSuperview];  

    }  

    [btnArray removeAllObjects];  

    int number = [textFieldNumber.text intValue];  

    for(i=0; i<number; ++i)  

        button = [UIButton buttonWithType:UIButtonTypeRoundedRect];  

        [button setTitle:[NSString stringWithFormat:@"%d", i] forState:UIControlStateNormal];  

        button.frame = CGRectMake(10, 10 + i * 40, self.view.frame.size.width - 20, 30);  

        [button addTarget:self action:@selector(btnAlert:) forControlEvents:UIControlEventTouchUpInside];  

        [btnArray addObject:button];  

        [scrollView addSubview:button];  

    //設定UIScrollView中要滾動的視窗大小(很重要)  

    scrollView.contentSize = CGSizeMake(self.view.frame.size.width, number * 40 + 10);  

-(IBAction)btnAlert:(id)sender  

    UIButton * btn = (UIButton *)sender;  

    NSString * str = [NSString stringWithFormat:@"您按下了 %@ 鍵", btn.currentTitle];  

    UIAlertView * alterview = [[UIAlertView alloc] initWithTitle:@"" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];   

    [alterview show];   

    [alterview release];   

- (void)scrollViewDidScroll:(UIScrollView *)scrollView  

    NSLog(@"scrollViewDidScroll");  

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView  

    NSLog(@"scrollViewWillBeginDragging");  

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate  

    NSLog(@"scrollViewDidEndDragging");  

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView  

    NSLog(@"scrollViewWillBeginDecelerating");  

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView  

    NSLog(@"scrollViewDidEndDecelerating");  

- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView  

    NSLog(@"scrollViewShouldScrollToTop");  

    return YES;  

- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView  

    NSLog(@"scrollViewDidScrollToTop");  

- (void)viewDidUnload  

    textFieldNumber = nil;  

    btnStart = nil;  

    scrollView = nil;  

    btnArray = nil;  

- (void)dealloc  

    [super dealloc];  

    [textFieldNumber release];  

    [btnStart release];  

    [scrollView release];  

    [btnArray release];  

說明:

在 Interface Builder 中,我們使用連線來關聯控件與IBAction,用代碼完成的話則是:

addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents  

其中action是@selector(actionFunction:),一定不要忘記最後的冒号!

要使用 UIScrollView,則必須實作 UIScrollViewDelegate,該Delegate定義如下:

@protocol UIScrollViewDelegate<NSObject>  

@optional  

- (void)scrollViewDidScroll:(UIScrollView *)scrollView;                                               // any offset changes  

- (void)scrollViewDidZoom:(UIScrollView *)scrollView __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_2); // any zoom scale changes  

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView;                              // called on start of dragging (may require some time and or distance to move)  

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate; // called on finger up if user dragged. decelerate is true if it will continue moving afterwards  

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView;   // called on finger up as we are moving  

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView;      // called when scroll view grinds to a halt  

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView; // called when setContentOffset/scrollRectVisible:animated: finishes. not called if not animating  

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView;     // return a view that will be scaled. if delegate returns nil, nothing happens  

- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_2); // called before the scroll view begins zooming its content  

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale; // scale between minimum and maximum. called after any 'bounce' animations  

- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView;   // return a yes if you want to scroll to the top. if not defined, assumes YES  

- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView;      // called when scrolling animation finished. may be called immediately if already at top  

有幾個是比較重要的:

scrollViewDidScroll:scrollView隻要在滾動就會觸發該方法(無論是被使用者拖動還是在拖動後scrollView由于慣性繼續滾動一點距離)

scrollViewWillBeginDragging:scrollView被使用者拖動前就會觸發該方法

scrollViewDidEndDragging:scrollView被使用者拖動結束後就會觸發該方法

scrollViewWillBeginDecelerating:scrollView在拖動後繼續滾動前就會觸發該方法

scrollViewDidEndDecelerating:scrollView在拖動後繼續滾動後停止就會觸發該方法

scrollViewShouldScrollToTop:傳回YES或NO,表示是否支援使用者點選螢幕頂端的狀态條後scrollView滾動到頂端(預設YES)

scrollViewDidScrollToTop:使用者點選螢幕頂端的狀态條後scrollView滾動到頂端後會觸發該方法(scrollViewShouldScrollToTop如果傳回NO,則該方法不會被觸發)

UIScrollView的常用屬性如下:

scrollView.pagingEnabled = NO;  

//劃動過程中顯示水準滾動條(如果有)  

scrollView.showsHorizontalScrollIndicator = YES;  

//劃動過程中顯示垂直滾動條(如果有)  

scrollView.showsVerticalScrollIndicator = YES;  

//點選頂部的狀态欄滾動到首  

scrollView.scrollsToTop = YES;  

scrollView.delegate = self;  

scrollView.contentSize = CGRect  

pagingEnabled:是否以整數倍的UIScrollView大小滾動(如果是用于圖檔類的UIScrollView,該值應該設定為YES,如果是用于顯示文本類的UIScrollView或者類似與本例的允許使用者滾動到任意位置的情況時應該設定為NO)

contentOffset:UIScrollView中content的左上角坐标

contentSize:UIScrollView中content的大小,該值與UIScrollView的大小決定滾動條的長短

decelerating:UIScrollView在拖動放手後是否仍在由于慣性繼續滾動中

dragging:UIScrollView是否正在被使用者拖動

showsHorizontalScrollIndicator:是否顯示水準滾動條

showsVerticalScrollIndicator:是否顯示垂直滾動條

另外例子中還介紹了如何用代碼(而不是Interface Builder)建立GUI控件,可以看看。

運作結果:

初始界面:

iPhone開發之UIScrollView初步

輸入20,按開始鍵,生成了20個UIButton:

iPhone開發之UIScrollView初步

劃動螢幕,出現滾動條:

iPhone開發之UIScrollView初步

點選任意一個按鈕:

iPhone開發之UIScrollView初步

輸入小一點的數字:

iPhone開發之UIScrollView初步

Console輸出結果如下:

iPhone開發之UIScrollView初步

下面介紹方法2:

和方法1類似,不過建立一個 Window-based Application,名稱是Scroll2:

iPhone開發之UIScrollView初步

建立一個基于UIView的子類,名稱是ScrollView

iPhone開發之UIScrollView初步

3.

修改 Scroll2AppDelegate.m 如下:

//  Scroll2AppDelegate.m  

//  Scroll2  

#import "Scroll2AppDelegate.h"  

#import "ScrollView.h"  

@implementation Scroll2AppDelegate  

@synthesize window;  

#pragma mark -  

#pragma mark Application lifecycle  

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  

    //注意這裡的坐标,是除去了頂部的狀态欄之後的剩餘部分  

    ScrollView * view = [[ScrollView alloc] initWithFrame:CGRectMake(0, 20, 320, 460)];  

    [window addSubview:view];  

    [window makeKeyAndVisible];  

    [window release];  

方法1我們用的是UIViewController,方法2我們直接用了UIView,都是可以的。

修改 ScrollView.h

//  ScrollView.h  

//  Copyright 2012 __MyCompanyName__. All rights reserved.  

@interface ScrollView : UIView<UIScrollViewDelegate>  

方法2實作了UIScrollViewDelegate的是UIView,而不是方法1中的UIViewController,都是可以的

修改 ScrollView.m

//  ScrollView.m  

@implementation ScrollView  

- (id)initWithFrame:(CGRect)frame  

    if ((self = [super initWithFrame:frame]))  

        self.backgroundColor = [UIColor yellowColor];  

        int widthOut = self.frame.size.width;  

        int widthIn = widthOut - 20;  

        btnArray = [[NSMutableArray alloc] init];  

        //聲明一個 UITextField  

        textFieldNumber = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, widthIn - 70, 30)];  

        textFieldNumber.backgroundColor = [UIColor whiteColor];  

        textFieldNumber.borderStyle = UITextBorderStyleRoundedRect;  

        [self addSubview:textFieldNumber];  

        //聲明一個 UIButton  

        btnStart = [UIButton buttonWithType:UIButtonTypeRoundedRect];  

        [btnStart setTitle:@"開始" forState:UIControlStateNormal];  

        btnStart.frame = CGRectMake(widthIn - 50, 10, 60, 30);  

        [btnStart addTarget:self action:@selector(btnStartAction:) forControlEvents:UIControlEventTouchUpInside];  

        [self addSubview:btnStart];  

        //聲明一個 UIScrollView  

        scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 50, widthOut, self.frame.size.height - 50)];  

        scrollView.backgroundColor = [UIColor redColor];  

        //任意劃動  

        scrollView.pagingEnabled = NO;  

        //劃動過程中顯示水準滾動條(如果有)  

        scrollView.showsHorizontalScrollIndicator = YES;  

        //劃動過程中顯示垂直滾動條(如果有)  

        scrollView.showsVerticalScrollIndicator = YES;  

        //點選頂部的狀态欄滾動到首  

        scrollView.scrollsToTop = YES;  

        scrollView.delegate = self;  

        [self addSubview:scrollView];  

    return self;  

        button.frame = CGRectMake(10, 10 + i * 40, self.frame.size.width - 20, 30);  

    scrollView.contentSize = CGSizeMake(self.frame.size.width, number * 40 + 10);  

我們将初始化代碼放在了[UIView initWithFrame]中,注意到我們在Scroll2AppDelegate.m中調用了initWithFrame方法,傳入了一個CGRect的視窗大小。總的來說,方法1中的self.view.xxx隻要改成方法2中的self.xxx就可以了。由此可見iPhone開發的靈活性。對于一個界面,即可以使用UIViewController(内包含一個UIView,就像方法1),也可以直接使用UIView(方法2),很友善。

運作結果與方法1完全一樣,故不在贅述。

最後我把兩種方法的完整代碼一起打包上傳上來了:

<a href="http://download.csdn.net/detail/htttw/4516528">http://download.csdn.net/detail/htttw/4516528</a>

本文轉自夏雪冬日部落格園部落格,原文連結:http://www.cnblogs.com/heyonggang/p/3497472.html,如需轉載請自行聯系原作者