我有一个简单的应用程序,不需要使用UITableViewController来构建。是否有可能为简单的UIViewController创建“下拉刷新”功能?
是的,有。事实上,要使用UIRefreshControl
只需要满足一个条件 - 你可以将UIRefreshControl
放在UIScrollView
或其子类中(例如UITableView
或UICollectionView
)。
Swift示例代码:
override func viewDidLoad() {
{
super.viewDidLoad()
//...
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(didPullToRefresh), forControlEvents: .ValueChanged)
scrollView.addSubview(refreshControl)
}
func didPullToRefresh() {
}
在Objective-c中的示例代码:
- (void)viewDidLoad
{
[super viewDidLoad];
//...
UIRefreshControl *refreshControl = [UIRefreshControl new];
[refreshControl addTarget:self action:@selector(didPullToRefresh) forControlEvents:UIControlEventValueChanged];
[self.scrollView addSubview:refreshControl];
}
- (void)didPullToRefresh
{
}
UIScrollView
(和其子类,UITableView
和UICollectionView
)上有一个refreshControl
属性。
来自Apple文档的代码:https://developer.apple.com/documentation/uikit/uirefreshcontrol#//apple_ref/occ/instm/UIRefreshControl
func configureRefreshControl () {
// Add the refresh control to your UIScrollView object.
myScrollingView.refreshControl = UIRefreshControl()
myScrollingView.refreshControl?.addTarget(self, action:
#selector(handleRefreshControl),
for: .valueChanged)
}
@objc func handleRefreshControl() {
// Update your content…
// Dismiss the refresh control.
DispatchQueue.main.async {
self.myScrollingView.refreshControl?.endRefreshing()
}
}