網頁

2012年9月23日 星期日

UIPageControl

使用 UIPageControl 與 UIScrollView 來實作畫面切換的效果


 
@interface ViewController : UIViewController 
{
    IBOutlet UIScrollView* scrollView;
    IBOutlet UIPageControl* pageControl;
}

@property (nonatomic, retain) UIView *scrollView;
@property (nonatomic, retain) UIPageControl* pageControl;

- (IBAction)changeCurrentPage:(UIPageControl *)sender ;
 

@synthesize scrollView;
@synthesize pageControl;

- (void)viewDidLoad
{
    [super viewDidLoad];
 // Do any additional setup after loading the view, typically from a nib.
    
    //UIPageControl設定
    [pageControl setNumberOfPages:7];
    [pageControl setCurrentPage:0];
    
    //UIScrollView設定
    [scrollView setPagingEnabled:YES];
    [scrollView setShowsHorizontalScrollIndicator:NO];
    [scrollView setShowsVerticalScrollIndicator:NO];
    [scrollView setScrollsToTop:NO];
    [scrollView setDelegate:self];
    
    CGFloat width, height;
    width  = scrollView.frame.size.width;
    height = scrollView.frame.size.height;
    [scrollView setContentSize:CGSizeMake(width * 7, height)];
    
    
    //製作ScrollView的內容
    for (int i=0; i!=pageControl.numberOfPages; i++) {
        CGRect frame = CGRectMake(width*i, 0, width, height);
        UIView *view = [[UIView alloc]initWithFrame:frame];
        
        CGFloat r, g ,b;
        r = (arc4random() % 10) / 10.0;
        g = (arc4random() % 10) / 10.0;
        b = (arc4random() % 10) / 10.0;
        [view setBackgroundColor:[UIColor colorWithRed:r green:g blue:b alpha:0.3]];
        
        
        [scrollView addSubview:view];
    }
  
}

#pragma -mark
#pragma -mark ScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)sender {
    CGFloat width = scrollView.frame.size.width;
    NSInteger currentPage = ((scrollView.contentOffset.x - width / 2) / width) + 1;
    [pageControl setCurrentPage:currentPage];
}



- (IBAction)changeCurrentPage:(UIPageControl *)sender {

    NSLog(@"nothing happen here");
    NSInteger page = pageControl.currentPage;
    
    CGFloat width, height;
    width = scrollView.frame.size.width;
    height = scrollView.frame.size.height;
    CGRect frame = CGRectMake(width*page, 0, width, height);
    
    [scrollView scrollRectToVisible:frame animated:YES];
}

沒有留言:

張貼留言

注意:只有此網誌的成員可以留言。