Swift中如何修改UITableView的下拉刷新图标?
修改UITableView下拉刷新图标的实现方案
你可以通过给系统UIRefreshControl添加自定义子视图的方式替换默认图标,以下是具体实现步骤和代码:
步骤1:定义自定义图标视图
在你的ViewController类中声明全局的UIImageView,用于承载自定义刷新图标:
private var customRefreshIcon: UIImageView!
步骤2:初始化RefreshControl并添加自定义图标
替换你原有的RefreshControl初始化代码,添加自定义图标并设置相关属性:
let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(pullToRefresh(refresh:)), for: .valueChanged) refreshControl.backgroundColor = .clear refreshControl.tintColor = .clear // 创建自定义图标视图 customRefreshIcon = UIImageView(image: UIImage(named: "your-custom-refresh-icon")) customRefreshIcon.contentMode = .scaleAspectFit customRefreshIcon.frame = CGRect(x: 0, y: 0, width: 30, height: 30) // 将图标居中放置在refreshControl内 customRefreshIcon.center = refreshControl.center refreshControl.addSubview(customRefreshIcon) tableView.refreshControl = refreshControl // 监听scrollView的滚动偏移,控制图标动画 tableView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
步骤3:实现滚动监听与图标动画逻辑
通过KVO监听scrollView的滚动状态,根据下拉进度和刷新状态控制图标旋转动画:
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard keyPath == "contentOffset", let scrollView = object as? UIScrollView else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) return } let offsetY = scrollView.contentOffset.y // 下拉过程中根据偏移量旋转图标 if offsetY < -60 { // 60为系统refreshControl的默认触发高度,可按需调整 let progress = abs(offsetY) / 60 customRefreshIcon.transform = CGAffineTransform(rotationAngle: CGFloat.pi * 2 * progress) } else if refreshControl.isRefreshing { // 刷新状态下持续旋转图标 if customRefreshIcon.layer.animation(forKey: "rotation") == nil { let rotationAnim = CABasicAnimation(keyPath: "transform.rotation.z") rotationAnim.toValue = CGFloat.pi * 2 rotationAnim.duration = 0.8 rotationAnim.repeatCount = .infinity customRefreshIcon.layer.add(rotationAnim, forKey: "rotation") } } else { // 结束刷新后重置图标状态 customRefreshIcon.layer.removeAnimation(forKey: "rotation") customRefreshIcon.transform = .identity } }
步骤4:完善刷新方法与资源清理
确保你的下拉刷新方法正常结束刷新,并在页面销毁时移除观察者:
@objc func pullToRefresh(refresh: UIRefreshControl) { // 这里执行你的业务刷新逻辑 DispatchQueue.main.asyncAfter(deadline: .now() + 2) { refresh.endRefreshing() } } deinit { tableView.removeObserver(self, forKeyPath: "contentOffset") }
注意事项
- 将代码中的
"your-custom-refresh-icon"替换为你项目中实际的图标资源名称 - 可根据需求调整图标的尺寸、位置,以及动画的速度、旋转角度等参数
- 如果不需要下拉过程中的进度动画,可简化监听逻辑,仅在刷新状态下添加旋转动画
内容的提问来源于stack exchange,提问作者androidisgood
相关产品推荐
相关产品推荐

