标签:
1 UIScrollView无限滚动 2 3 #import "ViewController.h" 4 5 #define kCount 8 6 7 @interface ViewController () <UIScrollViewDelegate> 8 { 9 UIImageView *_reusableView; // 循环利用的 10 UIImageView *_centerView; // 中间的 11 } 12 @property (weak, nonatomic) IBOutlet UIScrollView *scrollView; 13 @end 14 15 @implementation NJViewController 16 17 - (void)viewDidLoad 18 { 19 [super viewDidLoad]; 20 21 CGFloat w = _scrollView.frame.size.width; 22 NSLog(@"%f",w); 23 CGFloat h = _scrollView.frame.size.height; 24 _scrollView.pagingEnabled = YES; 25 _scrollView.contentSize = CGSizeMake(w * 3, 0); 26 _scrollView.contentOffset = CGPointMake(w, 0); 27 _scrollView.showsHorizontalScrollIndicator = NO; 28 29 _centerView = [[UIImageView alloc] init]; 30 _centerView.image = [UIImage imageNamed:@"00.jpg"]; 31 _centerView.frame = CGRectMake(w, 0, w, h); 32 _centerView.tag = 0; 33 [_scrollView addSubview:_centerView]; 34 35 _reusableView = [[UIImageView alloc] init]; 36 _reusableView.frame = _scrollView.bounds; 37 } 38 39 - (void)scrollViewDidScroll:(UIScrollView *)scrollView 40 { 41 CGFloat offsetX = scrollView.contentOffset.x; 42 CGFloat w = scrollView.frame.size.width; 43 NSLog(@"offsetX = %f and _centerView.frame.origin.x = %f",offsetX,_centerView.frame.origin.x); 44 // 1.设置 循环利用view 的位置 45 CGRect f = _reusableView.frame; 46 int index = 0; 47 if (offsetX > _centerView.frame.origin.x) { // 显示在最右边 48 NSLog(@"scrollView.contentSize.width = %f",scrollView.contentSize.width); 49 f.origin.x = scrollView.contentSize.width - w; 50 51 index = _centerView.tag + 1; 52 if (index >= kCount) index = 0; 53 } else { // 显示在最左边 54 f.origin.x = 0; 55 56 index = _centerView.tag - 1; 57 if (index < 0) index = kCount - 1; 58 } 59 _reusableView.frame = f; 60 _reusableView.tag = index; 61 NSString *icon = [NSString stringWithFormat:@"0%d.jpg", index]; 62 _reusableView.image = [UIImage imageNamed:icon]; 63 64 // 2.显示了 最左 或者 最右 的图片 65 if (offsetX <= 0 || offsetX >= w * 2) { 66 // 2.1.交换 中间的 和 循环利用的 67 UIImageView *temp = _centerView; 68 _centerView = _reusableView; 69 _reusableView = temp; 70 71 // 2.2.设置显示位置 72 _centerView.frame = _reusableView.frame; 73 scrollView.contentOffset = CGPointMake(w, 0); 74 75 [_reusableView removeFromSuperview]; 76 } else { 77 [_scrollView addSubview:_reusableView]; 78 } 79 } 80 @end
标签:
原文地址:http://www.cnblogs.com/songxing10000/p/4440315.html