这些 UIScrollView 分类使得向任何 UIScrollView(或其子类)添加下拉刷新和无限滚动功能变得非常简单。SVPullToRefresh 通过 Objective-C 运行时而不是依赖委托和/或继承 UIViewController
来添加以下 3 个方法到 UIScrollView
- (void)addPullToRefreshWithActionHandler:(void (^)(void))actionHandler;
- (void)addPullToRefreshWithActionHandler:(void (^)(void))actionHandler position:(SVPullToRefreshPosition)position;
- (void)addInfiniteScrollingWithActionHandler:(void (^)(void))actionHandler;
注意:如果您的项目不使用 ARC(自动引用计数):您必须在“目标设置”>“构建阶段”>“编译源”中添加 -fobjc-arc
编译器标志到 UIScrollView+SVPullToRefresh.m
和 UIScrollView+SVInfiniteScrolling.m
。
SVPullToRefresh/SVPullToRefresh
文件夹拖入您的项目。UIScrollView+SVPullToRefresh.h
和/或 UIScrollView+SVInfiniteScrolling.h
(在 /Demo
中查看示例 Xcode 项目)
[tableView addPullToRefreshWithActionHandler:^{
// prepend data to dataSource, insert cells at top of table view
// call [tableView.pullToRefreshView stopAnimating] when done
}];
或者如果您想要从底部下拉刷新
[tableView addPullToRefreshWithActionHandler:^{
// prepend data to dataSource, insert cells at top of table view
// call [tableView.pullToRefreshView stopAnimating] when done
} position:SVPullToRefreshPositionBottom];
如果您想以编程方式触发刷新(例如在 viewDidAppear:
中),您可以使用以下命令来实现:
[tableView triggerPullToRefresh];
您可以通过设置 showsPullToRefresh
属性来临时隐藏下拉刷新视图
tableView.showsPullToRefresh = NO;
可以使用以下属性和方法来自定义下拉刷新视图:
@property (nonatomic, strong) UIColor *arrowColor;
@property (nonatomic, strong) UIColor *textColor;
@property (nonatomic, readwrite) UIActivityIndicatorViewStyle activityIndicatorViewStyle;
- (void)setTitle:(NSString *)title forState:(SVPullToRefreshState)state;
- (void)setSubtitle:(NSString *)subtitle forState:(SVPullToRefreshState)state;
- (void)setCustomView:(UIView *)view forState:(SVPullToRefreshState)state;
您可以通过滚动视图的 pullToRefreshView
属性访问这些属性。
例如,您可以使用以下代码设置 arrowColor
属性:
tableView.pullToRefreshView.arrowColor = [UIColor whiteColor];
[tableView addInfiniteScrollingWithActionHandler:^{
// append data to data source, insert new cells at the end of table view
// call [tableView.infiniteScrollingView stopAnimating] when done
}];
如果您想在 viewDidAppear:
中等情况下以编程方式触发加载,您可以使用以下方法来实现:
[tableView triggerInfiniteScrolling];
您可以通过设置 showsInfiniteScrolling
属性来临时隐藏无限滚动视图
tableView.showsInfiniteScrolling = NO;
可以使用以下方法来自定义无限滚动视图:
- (void)setActivityIndicatorViewStyle:(UIActivityIndicatorViewStyle)activityIndicatorViewStyle;
- (void)setCustomView:(UIView *)view forState:(SVInfiniteScrollingState)state;
您可以通过滚动视图的 infiniteScrollingView
属性访问这些属性。
SVPullToRefresh通过添加新的公共方法和动态属性扩展了UIScrollView
。
它使用键值观察来跟踪scrollView的contentOffset
。
SVPullToRefresh是由Sam Vermette和项目的贡献者带来的。如果您有功能建议或错误报告,请通过发送合并请求或通过创建新问题来提供帮助。如果您正在您的项目中使用SVPullToRefresh,署名将是很棒的。
对于@seb_morel关于揭开Objective-C运行时面纱的讨论表示衷心的感谢,这段讨论对这个项目有很大帮助。
向发明下拉刷新的Loren Brichter致敬。