联系客服:400-805-1963

UIPageControl与UIScrollView的联合使用
更新:HHH   时间:2023-1-7


 

  1. - (id)initWithFrame:(CGRect)frame 
  2. { 
  3.     self = [super initWithFrame:frame]; 
  4.     if (self) { 
  5.         // Initialization code        
  6.         _statisScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(7, 9, frame.size.width - 23, frame.size.height - 45)]; 
  7.         _statisScrollView.contentSize = CGSizeMake(_statisScrollView.frame.size.width * 2, _statisScrollView.frame.size.height); 
  8.         _statisScrollView.backgroundColor = [UIColor clearColor]; 
  9.         _statisScrollView.pagingEnabled = YES; 
  10.         _statisScrollView.showsHorizontalScrollIndicator = NO; 
  11.         _statisScrollView.delegate = self; 
  12.         [self addSubview:_statisScrollView]; 
  13.         [_statisScrollView release]; 
  14.          
  15.         _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, frame.size.height - 40, frame.size.width, 20)]; 
  16.         _pageControl.backgroundColor = [UIColor clearColor]; 
  17.         _pageControl.currentPage = 0; 
  18.         _pageControl.numberOfPages = 2; 
  19.         [_pageControl addTarget:self action:@selector(getChangePage:) forControlEvents:UIControlEventValueChanged]; 
  20.         [self addSubview:_pageControl]; 
  21.         [_pageControl release];         
  22.     } 
  23.     return self; 
  24. } 
  25.  
  26. - (void)getChangePage:(UIPageControl *)pageControl 
  27. { 
  28.     int page = pageControl.currentPage; 
  29.      
  30.     CGRect frame = _statisScrollView.frame; 
  31.     frame.origin.x = frame.size.width * page;//根据页数计算要显示的坐标区域 
  32.     frame.origin.y = 0; 
  33.     [_statisScrollView scrollRectToVisible:frame animated:YES];//显示 
  34. } 
  35. #pragma mark UIScrollViewDelagete 
  36. - (void)scrollViewDidScroll:(UIScrollView *)scrollView 
  37. { 
  38.     CGFloat pageWidth = scrollView.frame.size.width; 
  39.     int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;//根据坐标区域的位置计算当前第几页 
  40.     _pageControl.currentPage = page;//页数赋值给pageControl的当前页 
  41. } 

 

返回移动开发教程...