通过以下方法创建滚动视图:
self.scrollView = [[LTInfiniteScrollView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 200)];
[self.view addSubview:self.scrollView];
self.scrollView.dataSource = self;
[self.scrollView reloadDataWithInitialIndex: 0];
然后实现 LTInfiniteScrollViewDataSource
协议
@protocol LTInfiniteScrollViewDataSource<NSObject>
- (UIView *)viewAtIndex:(NSInteger)index reusingView:(UIView *)view;
- (NSInteger)numberOfViews;
- (NSInteger)numberOfVisibleViews;
@end
示例代码
- (NSInteger)numberOfViews
{
// you can set it to a very big number to mimic the infinite behavior, no performance issue here
return 9999;
}
- (NSInteger)numberOfVisibleViews
{
return 5;
}
- (UIView *)viewAtIndex:(NSInteger)index reusingView:(UIView *)view;
{
if (view) {
((UILabel*)view).text = [NSString stringWithFormat:@"%ld", index];
return view;
}
UILabel *aView = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 64, 64)];
aView.backgroundColor = [UIColor blackColor];
aView.layer.cornerRadius = 32;
aView.layer.masksToBounds = YES;
aView.backgroundColor = [UIColor colorWithRed:0/255.0 green:175/255.0 blue:240/255.0 alpha:1];
aView.textColor = [UIColor whiteColor];
aView.textAlignment = NSTextAlignmentCenter;
aView.text = [NSString stringWithFormat:@"%ld", index];
return aView;
}
LTInfinitedScrollView
接口
@interface LTInfiniteScrollView: UIView
@property (nonatomic, readonly) NSInteger currentIndex;
@property (nonatomic, weak) id<LTInfiniteScrollViewDataSource> dataSource;
@property (nonatomic, weak) id<LTInfiniteScrollViewDelegate> delegate;
@property (nonatomic) BOOL verticalScroll;
@property (nonatomic) BOOL scrollEnabled;
@property (nonatomic) BOOL pagingEnabled;
@property (nonatomic) BOOL bounces;
@property (nonatomic) UIEdgeInsets contentInset;
@property (nonatomic) NSInteger maxScrollDistance;
- (void)reloadDataWithInitialIndex:(NSInteger)initialIndex;
- (void)scrollToIndex:(NSInteger)index animated:(BOOL)animated;
- (UIView *)viewAtIndex:(NSInteger)index;
- (NSArray *)allViews;
@end
如果您想在滚动期间应用任何动画,实现 LTInfiniteScrollViewDelegate
协议
@protocol LTInfiniteScrollViewDelegate<NSObject>
- (void)updateView:(UIView *)view withProgress:(CGFloat)progress scrollDirection:(ScrollDirection)direction;
@end
进度值的值表示该视图的相对位置,如果有5个可见视图,值将介于-2到2之间
| |
|-2 -1 0 1 2|
| |
您可以克隆项目并查看示例以获取详细信息。
以下是 Swift 版本:https://github.com/ltebean/LTInfiniteScrollView-Swift