Swift 自定义炫酷下拉刷新效果

时间:2023-03-09 01:25:52
Swift 自定义炫酷下拉刷新效果

先来看下效果

Swift 自定义炫酷下拉刷新效果
下拉刷新

其实下拉刷新没大家想得那么难。本文已第二个为例子。给大家讲解下下拉刷新的做法(完整代码后面会放上)

首先,先搞一个single View Application 。然后进Main.storyboard中,选中viewController

Swift 自定义炫酷下拉刷新效果
t1.png

按照图中方法,加一个导航。 然后然后拖一个tableview到viewController上。设置下四边的约束都为0 。
选中tableview 把有边框中Prototype Cells 设置为1 。选中Cell右边框中Identifier 设置为Cell
,然后再设置下代理

Swift 自定义炫酷下拉刷新效果
t2.png

这些都是些基础的操作,不再赘述了。
然后代码中也是很基础的 搞出点数据就行了

import UIKit

class SecondViewController: UIViewController,UITableViewDataSource,UITableViewDelegate , RefreshDelegate{

    @IBOutlet weak var tableView:UITableView!

    var datas = ["第一行","第二行","第三行","第四行","第五行"]

    override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
} override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
} func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath);
cell.textLabel?.text = datas[indexPath.row]
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datas.count;
}
}

下来就该自定义我们的刷新了。。

下拉刷新,能下拉肯定是scrollview 。所以我们需要scrollview的一些方法。这里我们的view继承自UIView ,实现
UIScrollViewDelegate协议

class DZRefreshViewTwo: UIView,UIScrollViewDelegate {

首先我们定义一个scrollview 作为成员变量

var scrollView:UIScrollView!

由于我们这个view是放在一个scrollview中的 所以我们初始化的时候需要传入一个scrollview来作为我们view的父容器

    init(frame: CGRect , scrollView:UIScrollView) {
super.init(frame: frame)
self.scrollView = scrollView
scrollView.delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init(scrollView:UIScrollView){
if let sv = scrollView.superview {
self.init(frame:CGRectMake(0,-80, sv.frame.size.width ,80),scrollView:scrollView)
}else{
self.init(frame:CGRectMake(0,-80, scrollView.frame.size.width ,80),scrollView:scrollView)
}
}

这里我们添加了几个构造方法 , 用户可以自己制定frame , 用户如果不想自己指定我们还提供了默认的frame 。这里为啥要判断 if let sv = scrollView.superview 有没有父容器呢?因为我们这个scrollview有可能是通过约束放上去得 frame属性就不准了 ,用它父类的比较准确 。

这里80是我们设定的默认宽度,Y是-80就是初始是看不到的。只有下拉才能看到。所以下拉的过程中这个view要慢慢出现。这个view是放在 scrollview中的。所以只需要操作scrollview即可,这里需要使用scrollview计算下拉的进度,把这个height(80)全部 拉出来的时候就是1

先声明一个progress的成员变量var progress:CGFloat = 0.0 然后实现scrollview协议的下面方法

   //计算进度
func scrollViewDidScroll(scrollView: UIScrollView) {
let offY = max(-1*(scrollView.contentOffset.y+scrollView.contentInset.top),0)
progress = min(offY / self.frame.size.height , 1.0)
}

这里就是计算了拉下来的长度与height的比 ,只有contentOffset和contentInset是什么意思, 网上查查 这些都是scrollview的基础。不再本例子范围内

我们例子中 在下拉的同时,有一个灰色一坨被拉出来(哈哈--粗鲁了。)

所以每次计算完进度后要进行绘制。绘制图形 是CAShapeLayer的强项,这里我们先声明一个CAShapeLayer的成员常量

    var shapeLayer = CAShapeLayer()

然后在初始化的时候给出边的颜色并添加到view的layer上

 shapeLayer.strokeColor = UIColor.grayColor().CGColor
layer.addSublayer(shapeLayer)

其他的属性,要在下拉的时候绘制,添加绘制的方法

 //绘制
func reDraw(offY:CGFloat){
shapeLayer.fillColor = UIColor.grayColor().CGColor
let y = frame.size.height - offY + 1
let width = frame.size.width * progress * 0.8 > 15 ? 15:frame.size.width * progress * 0.8
shapeLayer.path = UIBezierPath(ovalInRect: CGRectMake((frame.size.width/2) - 7.5 , y , width , frame.size.height * progress * 0.8)).CGPath }

这里指定填充颜色 , 利用UIBezierPath(ovalInRect:CGRect) 方法,其实就是在一个矩形中画圆或者椭圆。我们只需要控制矩形的位置和长宽就行了 , 这里高度和长宽都会随下拉变化 。 具体度大家也可以自己把握。也可以按照我上面设置的 。

然后把这个方法添加到func scrollViewDidScroll(scrollView: UIScrollView)的最后面

我们到现在只做了下拉过程中的部分 , 下拉结束呢 ,下拉结束的时候会调用scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) 我们在这个方法中进行刷新操作,开始刷新,既然开始刷新要判断是否正在刷新。 所以要先声明一个变量var isRefreshing = false

而且具体的刷新操作肯定不是放在本类执行 ,是要给使用此刷新控件的view执行,这里用一个代理方法

先声明一个协议

protocol RefreshDelegate{
func doRefresh(refreshView: DZRefreshViewTwo)
}

然后在本类声明这个代理的变量var delegate:RefreshDelegate?

在本类中添加一个开始动画的方法 ,后面使用

 func beginRefresh(){

}

这时候下拉结束的方法就可以这样写了

  func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if !isRefreshing && progress >= 1{
//执行刷新任务
delegate?.doRefresh(self)
beginRefresh()
}
}

beginRefresh中,首先要把这个view固定在视野中,然后去执行动画 。 执行动画的时候我们希望下拉过程中不重新绘制了 我们定义一个变量var isAnimating = false

func beginRefresh(){
isRefreshing = true
isAnimating = true
UIView.animateWithDuration(0.3) {
var inSet = self.scrollView.contentInset;
inSet.top += self.frame.size.height
self.scrollView.contentInset = inSet
}
//动画
let keyAnimation = CAKeyframeAnimation(keyPath: "path")
keyAnimation.duration = 0.8
keyAnimation.values = [UIBezierPath(ovalInRect: CGRectMake((self.frame.size.width/2) - 20 , self.frame.size.height/2 - 15 , 10 , 10 )).CGPath ,
UIBezierPath(ovalInRect: CGRectMake((self.frame.size.width/2) - 8, self.frame.size.height/2 - 2 , 30 , 30 )).CGPath,
UIBezierPath(ovalInRect: CGRectMake((self.frame.size.width/2) - 18 , self.frame.size.height/2 - 18 , 20 , 20 )).CGPath,
UIBezierPath(ovalInRect: CGRectMake((self.frame.size.width/2) - 12 , self.frame.size.height/2 - 7 , 35 , 35 )).CGPath,
UIBezierPath(ovalInRect: CGRectMake((self.frame.size.width/2) - 17 , self.frame.size.height/2 - 17 , 28 , 28 )).CGPath,
UIBezierPath(ovalInRect: CGRectMake((self.frame.size.width/2) - 15 , self.frame.size.height/2 - 13 , 33 , 33 )).CGPath,
UIBezierPath(ovalInRect: CGRectMake((self.frame.size.width/2) - 15 , self.frame.size.height/2 - 15 , 30 , 30 )).CGPath
] self.shapeLayer.addAnimation(keyAnimation, forKey: nil) self.shapeLayer.path = UIBezierPath(ovalInRect: CGRectMake((self.frame.size.width/2) - 15 , self.frame.size.height/2 - 15 , 30 , 30 )).CGPath shapeLayer.fillColor = UIColor.clearColor().CGColor
shapeLayer.lineWidth = 4
shapeLayer.lineDashPattern = [2]
let baseAnimation = CABasicAnimation(keyPath: "strokeEnd")
baseAnimation.duration = 2
baseAnimation.fromValue = 0
baseAnimation.toValue = 1
baseAnimation.repeatDuration = 5
shapeLayer.addAnimation(baseAnimation, forKey: nil)
}

这个方法中前面 是固定住这个view然后,收松开后的动画了。。不多说了,大家任意发挥。可以搞自己喜欢的动画 。这里要有一个一直在走得效果我们设置strokeEnd从0-1 就是那个转得效果 。

shapeLayer.lineWidth = 4
shapeLayer.lineDashPattern = [2]

设置边框宽度 , 设置间隔,也可以设置多个如[2,4,3]这种 自己试试看效果

所以我们重新绘制的时候就需要判断是否正在动画 , 而且不需要这种间隔的效果了

//绘制
func reDraw(offY:CGFloat){
if !isAnimating {
shapeLayer.lineWidth = 0
shapeLayer.lineDashPattern = []
shapeLayer.fillColor = UIColor.grayColor().CGColor
let y = frame.size.height - offY + 1
let width = frame.size.width * progress * 0.8 > 15 ? 15:frame.size.width * progress * 0.8
shapeLayer.path = UIBezierPath(ovalInRect: CGRectMake((frame.size.width/2) - 7.5 , y , width , frame.size.height * progress * 0.8)).CGPath }
}

下载完成后需要结束动画 。 所以我们加了endRefresh方法

   func endRefresh(){
isRefreshing = false
isAnimating = false
UIView.animateWithDuration(0.3) {
var inSet = self.scrollView.contentInset;
inSet.top -= self.frame.size.height
self.scrollView.contentInset = inSet
}
}

代码并不多,这时候就可以使用了 。

首先 我们的viewController实现这个协议RefreshDelegate 。
然后在viewDidLoad中初始化

 let refreshView = DZRefreshViewTwo(scrollView: tableView)
refreshView.delegate = self
self.tableView.addSubview(refreshView)

然后实现协议方法就行了,

func doRefresh(refreshView: DZRefreshViewTwo) {
//在这里执行更新数据的操作 更新完执行endRefresh
}

我们这里模拟下,暂停4秒

  func doRefresh(refreshView: DZRefreshViewTwo) {
delay(4) {
refreshView.endRefresh()
}
} func delay(seconds: Double, completion:()->()) {
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64( Double(NSEC_PER_SEC) * seconds )) dispatch_after(popTime, dispatch_get_main_queue()) {
completion()
}
}

这时候执行效果如图

Swift 自定义炫酷下拉刷新效果
效果图
两个效果完整源码:https://github.com/smalldu/IOS-Animations
AnimationDemo7