iOS工作系列干货IOS特技

下拉刷新 - iOS开发

2016-02-14  本文已影响4968人  莫威權在B612等着那温柔的风
最终效果

前言

通过这篇文你会学到:

下拉刷新


首先自己弄好如图的TableView,这个自己弄吧。这篇文主要专注于下拉刷新。

tableView

添加TableView的映射到ViewControllertblDemo

@IBOutlet weak var tblDemo: UITableView!

要做出下拉刷新需要用到UIRefreshControl
在viewController添加变量:

var refreshControl: UIRefreshControl!

然后在viewDidLoad()添加:

refreshControl = UIRefreshControl()
//设置背景颜色
refreshControl.backgroundColor = UIColor.redColor()
//设置菊花转的颜色
refreshControl.tintColor = UIColor.yellowColor()

//往tableView添加刷新控件
tblDemo.addSubview(refreshControl)

运行如下:

red_yellow_refresh

个性化下拉刷新


原理:因为UIRefreshControl实际是UIView的子类,所以直接在上面添加view来覆盖默认的刷新菊花转view

1.使用xib创建view


首先弄出自己定制的view:

newFile.png view

文件名字为RefreshContents

name.png

接着在右边的侧边栏中设置view的大小

size.png set Size.png

然后一个个地将Label拖进去并设置好constrain:

fin.png

然后将里面的Label用tag标记,首先是‘我’为Tag 1,‘是’为 2,..以此类推:

tag.png

2.覆盖UIRefreshControl的默认view


    //存储定制好的view和label
    var customView: UIView!
    var labelsArray: Array<UILabel> = []
    
    func loadCustomRefreshContens(){
    //读取xib里的view
        let refreshContents = NSBundle.mainBundle().loadNibNamed("RefreshContents", owner: self, options: nil)
        
        customView = refreshContents[0] as! UIView
  //按照refreshControl的大小设置view的大小
        customView.frame = refreshControl.bounds
    
    //读取view 里 label 到labelsArray
        for var i=0; i < customView.subviews.count; ++i{
            labelsArray.append(customView.viewWithTag(i + 1) as! UILabel)
        }
     
     //覆盖默认view   
        refreshControl.addSubview(customView)
    }

接着在viewDidLoad()添加

loadCustomRefreshContents()

运行,下拉就能看到

firstStep.png

3.添加动画效果


animation.gif

观察图中的动画,可以将动画分解为以下两个步骤:

先在viewController定义下面的变量:

//用来判断是否可以执行动画,防止动画未完时又启动了动画
var isAnimating = false
 
var currentColorIndex = 0
 
var currentLabelIndex = 0

第一步的实现如下:

    func animateRefreshStep1(){
        isAnimating = true
        
        UIView.animateWithDuration(0.1, delay: 0.0, options: .CurveLinear, animations: {
                self.labelsArray[self.currentLabelIndex].transform = CGAffineTransformMakeRotation(CGFloat(M_PI_4))
            self.labelsArray[self.currentLabelIndex].textColor = self.getNextColor()
            
            
        }, completion: {(finished) -> Void in
            UIView.animateWithDuration(0.05, delay: 0.0, options: .CurveLinear, animations: {
                    self.labelsArray[self.currentLabelIndex].transform = CGAffineTransformIdentity
                self.labelsArray[self.currentLabelIndex].textColor = UIColor.blackColor()
                
                }, completion: {(fin) -> Void in
                    ++self.currentLabelIndex
                    
                    if self.currentLabelIndex < self.labelsArray.count{
                        self.animateRefreshStep1()
                    }
                    else{
                        self.animateRefreshStep2()
                    }
                
                }
            )
        })
    }
    
    //返回下个颜色
    func getNextColor() -> UIColor{
        var colorsArray: Array<UIColor> = [UIColor.magentaColor(),UIColor.brownColor(),UIColor.yellowColor(),UIColor.redColor(),UIColor.greenColor(),UIColor.blueColor(),UIColor.orangeColor()]
        if currentColorIndex == colorsArray.count{
            currentColorIndex = 0
        }
        
        let returnColor = colorsArray[currentColorIndex]
        ++currentColorIndex
        
        return returnColor
    }

第二步的实现:

    func animateRefreshStep2(){
        UIView.animateWithDuration(0.35, delay: 0.0, options: .CurveLinear, animations: {
                self.labelsArray[0].transform = CGAffineTransformMakeScale(1.5,1.5)
                self.labelsArray[1].transform = CGAffineTransformMakeScale(1.5,1.5)
                self.labelsArray[2].transform = CGAffineTransformMakeScale(1.5,1.5)
                self.labelsArray[3].transform = CGAffineTransformMakeScale(1.5,1.5)
                self.labelsArray[4].transform = CGAffineTransformMakeScale(1.5,1.5)
                self.labelsArray[5].transform = CGAffineTransformMakeScale(1.5,1.5)
                self.labelsArray[6].transform = CGAffineTransformMakeScale(1.5,1.5)
            
            
            }, completion: {(fin) -> Void in
                UIView.animateWithDuration(0.25, delay: 0.0, options: .CurveLinear, animations: {
                        self.labelsArray[0].transform = CGAffineTransformIdentity
                        self.labelsArray[1].transform = CGAffineTransformIdentity
                        self.labelsArray[2].transform = CGAffineTransformIdentity
                        self.labelsArray[3].transform = CGAffineTransformIdentity
                        self.labelsArray[4].transform = CGAffineTransformIdentity
                        self.labelsArray[5].transform = CGAffineTransformIdentity
                        self.labelsArray[6].transform = CGAffineTransformIdentity
                    
                    }, completion: {(fin) -> Void in
                        //如果还未结束刷新则回到第一步再来一次
                        if self.refreshControl.refreshing{
                            self.currentLabelIndex = 0
                            self.animateRefreshStep1()
                        }else{
                        //完成,设置为原始状态
                            self.isAnimating  = false
                            self.currentLabelIndex = 0
                            for var i = 0; i<self.labelsArray.count; ++i{
                                self.labelsArray[i].textColor = UIColor.blackColor()
                                self.labelsArray[i].transform = CGAffineTransformIdentity
                            }
                        }
                })
        
        })
    }

接着就是设置当下拉刷新时启动动画:

    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        if refreshControl.refreshing{
            if !isAnimating{
                animateRefreshStep1()
            }
        }
    }

运行就能见到动画效果了。

4.插入数据并且结束下拉刷新


这里为了模拟读取网络上的数据所以用NSTimer设置4秒的延迟。然后结束下拉刷新,并且插入数据。

定义如下函数:

    func doSomething(){
    //4秒后触发endOfWork
        timer = NSTimer.scheduledTimerWithTimeInterval(4.0, target: self, selector: "endOfWork", userInfo: nil, repeats: true)
    }

    func endOfWork(){
        //结束下拉刷新
        refreshControl.endRefreshing()
        
        timer.invalidate()
        timer = nil
        
        //插入数据
        insertLoveData()
    }
    
    func insertLoveData(){
        let lastIndexpath = NSIndexPath(forRow: dataArray.count, inSection: 0)
        
        //往数据里添加新的数据
        dataArray.append("其实我也喜欢你")
        
        //更新tableView数据
        tblDemo.beginUpdates()
        tblDemo.insertRowsAtIndexPaths([lastIndexpath], withRowAnimation: .Middle)
        tblDemo.endUpdates()
    }


接着在在scrollViewDidEndDecelerating插入doSomething如下:

    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        if refreshControl.refreshing{
            if !isAnimating{
                doSomething()
                animateRefreshStep1()
            }
        }
    }

运行,如下效果:

pullRefresh.gif

最后


因为写这文时刚好是情人节,所以就应下境。虐狗节快乐吧:)


(End And Thank U)
参考链接

源码下载

上一篇下一篇

猜你喜欢

热点阅读