2012年6月7日 星期四

UIPageControl

目的:切換頁面

Step1.拖拉三個View及Page Control控件,如下

Step2.ViewControl.h(需 import  QuartzCore.framework)
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>

@interface ViewController : UIViewController
{
    //頁面
    IBOutlet id page1;
    IBOutlet id page2;
    IBOutlet id page3;
   
    IBOutlet id pageControl;
   
    //記錄
    int prePage;//前一個頁數
    int curPage;//目的頁數
   
    CGPoint startOfPoint;//記錄座標點,往右或往左
}

//切換頁面
-(IBAction)turnPage:(UIPageControl *)sender;

@end

//切換頁面
-(IBAction)turnPage:(id)sender;
@end

Step3.建立關聯

Step4.ViewControl.m
//切換頁面
-(IBAction)turnPage:(UIPageControl *)sender{
    //目前頁面
    curPage =  [sender currentPage];
   
    CATransition *anim = [CATransition animation];
    [anim setDelegate:self];//代理人
    [anim setDuration:2.0f];//動畫執行時間
    [anim setType:kCATransitionPush];//動畫類別
   
    if(curPage > prePage){
        //目前頁數大於前頁
        [anim setSubtype:kCATransitionFromRight];//往右
    }else{
        [anim setSubtype:kCATransitionFromLeft];//往左
    }
   
    switch (curPage) {
        case 0://第一頁
            [self.view bringSubviewToFront:page1];
            break;
        case 1://第二頁
            [self.view bringSubviewToFront:page2];
            break;
        case 2://第三頁
            [self.view bringSubviewToFront:page3];
            break;
    }
   
    [[self.view layer]addAnimation:anim forKey:@"transition"];
    prePage = curPage;
}
//觸碰開始
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    startOfPoint = [touch locationInView:self.view];//存入點選畫的座標
}
//觸碰結束
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    //結束座標
    CGPoint endOfPoint = [touch locationInView:self.view];
    //目前頁數
    curPage = [pageControl currentPage];
   
    if(startOfPoint.x > endOfPoint.x){
        //往右
        [pageControl setCurrentPage:curPage+1];
        if (curPage==2) {
            return;
        }
    }else{
        //往左
        [pageControl setCurrentPage:curPage-1];
        if (curPage==0) {
            return;
        }
    }
    [self turnPage:pageControl];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
   
    //載入時,初始化
    prePage = 0;
    CGRect rect = self.view.frame;//struct 不需加point
    [page3 setFrame:rect];
    [self.view addSubview:page3];
   
    [page2 setFrame:rect];
    [self.view addSubview:page2];
   
    [page1 setFrame:rect];
    [self.view addSubview:page1];
}