您的位置:首页 > 移动开发 > Swift

swift详解之二十八---------自定义下拉刷新

2015-09-23 08:00 676 查看

swift详解之二十八———自定义下拉刷新

好久不写博客了 ,最近比较忙。swift学习稍微搁置了,昨天看了AppCoda的自定义下拉刷新 , 挺有心意的,也很简单。就顺便写写,在它的基础上添加了,下拉拉伸。OK先看下效果,基本都是按照它的思路实现的。



下拉的时候,从没有到慢慢的显示出来,再到拉长。

首先,创建一个single ViewController的项目 。然后在Main.storyboard上拖一个tableView。 四边的约束都设置成 0 。

在ViewController中声明
@IBOutlet weak var tb:UITableView!
,然后再在 Main.storyboard里面连线 。



右击就能看到这个菜单 , 点击tb旁边的空心圆,拖到tableView上就行了。

然后就是造数据,让我们的ViewController实现两个协议 ,其实这写都是UITableview的基本使用 。不再赘述可以看我前面关于UITableView的文章。

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate


//声明
var dataArr = ["第一行","第二行","第三行","第四行","第五行"]
//viewDidLoad中
 tb.delegate = self
 tb.dataSource = self


func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1;
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
        cell.textLabel!.text = dataArr[indexPath.row]
        return cell
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArr.count
    }

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 60.0
    }


以上是相关代码 。

现在运行APP应该只显示五行数据。下面添加系统的下拉刷新控件—
UIRefreshControl


声明一个变量
var refreshControl: UIRefreshControl!


在viewDidLoad中添加下面代码。

refreshControl = UIRefreshControl()
 tb.addSubview(refreshControl)


这时候运行代码下拉的时候就有有个菊花在转 。 但是不会停。用他们的原图吧。。



这里其实可以对UIRefreshControl进行自定义 。 可以设置其backgroundColor,tintColor等

可以添加下面两行代码到viewDidLoad中试试

refreshControl.backgroundColor = UIColor.redColor()
 refreshControl.tintColor = UIColor.yellowColor()




这里可以看到,它也是一个UIView.那么我们就可以自己去画一个uiview放在上面,执行我们自己的动画。下面通过xib画一个

这里我在xib中添加一个uiview把size改成Freeform。再添加五个label 。 (因为后面要单独做动画)

并且为每个设置好约束 。(最中间设置水平垂直居中,其他都是水平居中,设置好间隔就行了)




然后就是在ViewController中使用了。

首先声明两个变量

var customView: UIView!
var labelsArray: Array<UILabel> = []


第一个是那个容器 ,下面用于放五个label。stone

func loadCustomRefresh(){
        let refresh = NSBundle.mainBundle().loadNibNamed("View", owner: self, options: nil)
        customView = refresh[0] as! UIView
        customView.frame = refreshControl.frame

        for var i = 0 ; i < customView.subviews.count ; i++ {
           labelsArray.append(customView.viewWithTag(i+1) as! UILabel)
           self.labelsArray[i].alpha = 0
        }

        refreshControl.addSubview(customView)
    }


这个是加载xib并把那些label都加到数组最后把它加到刷新控件上。

在viewDIdLoad最后调用这个方法并修改

refreshControl.backgroundColor = UIColor.clearColor()
  refreshControl.tintColor = UIColor.clearColor()


这两个方法是让菊花和背景的颜色都变成透明 。

这时候运行app就看到我们自定义的这个view了

但是它并不会动,我们需要给它添加上动画效果 。

下拉从透明到显示,可以拉伸的效果。

大家可能注意到我上面loadCustomRefresh方法中有一句
self.labelsArray[i].alpha = 0
,设置成完全透明 , 初始是看不到的 , 然后再我们下拉的时候慢慢的显示 。用到UIScrollView中的
scrollViewDidScroll
方法

func scrollViewDidScroll(scrollView: UIScrollView) {
        let sg = ( scrollView.contentOffset.y * -1 ) / 60.0

        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            for var i=0; i<self.labelsArray.count; ++i {
                self.labelsArray[i].alpha = sg
                self.labelsArray[i].transform = CGAffineTransformMakeScale(sg>=1 ? 1:sg,sg)
            }
        }
    }


在下拉的过程中它的
contentOffset
一直在变化 , 我们根据它计算出一个比例 。控制透明度和缩放比例 。然后实时更新到界面上。因为要实时更新界面所以异步在主线程上更新。用到gcd。

这时候运行就有下拉的效果了。

文字动画

我们这里的文字动画分两部分

1、旋转45度变色

2、放大

我们需要分部去做 。

首先定义几个变量

var isAnimating = false
   var currentColorIndex = 0
   var currentLabelIndex = 0


isAnimating 当前动画是否正在放生 。

currentColorIndex 当前label的颜色。

currentLabelIndex 当前是哪个label(下标)

然后添加一个改变颜色的方法。里面只有五个颜色

func getNextColor() -> UIColor {
        var colorsArray: Array<UIColor> = [UIColor.magentaColor(), UIColor.brownColor(), UIColor.yellowColor(), UIColor.redColor(), UIColor.greenColor()]

        if currentColorIndex == colorsArray.count {
            currentColorIndex = 0
        }

        let returnColor = colorsArray[currentColorIndex]
        ++currentColorIndex

        return returnColor  
    }


这个可以随自己喜欢 。也可以随机颜色

然后,进行第一个动画

f

unc animateOne(){
        isAnimating = true
        UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in
            self.labelsArray[self.currentLabelIndex].transform = CGAffineTransformMakeRotation(CGFloat(M_PI_4))
            self.labelsArray[self.currentLabelIndex].textColor = self.getNextColor()

            }) { (finished) -> Void in

                UIView.animateWithDuration(0.1, delay: 0.0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in
                    self.labelsArray[self.currentLabelIndex].transform = CGAffineTransformIdentity
                    self.labelsArray[self.currentLabelIndex].textColor = UIColor.whiteColor()
                    }, completion: { (finished) -> Void in
                        ++self.currentLabelIndex

                        if self.currentLabelIndex < self.labelsArray.count {
                            self.animateOne()
                        }
                        else {
                            self.animateTwo()
                        }  
                })

        }

    }


动画部分就是一个旋转45度然后改变颜色 , 动画完成的时候执行另一个动画,首先将当前label平滑的恢复位置 , 然后判断后面还有没有其他label ,如果有 继续执行其他的,如果没有就执行第二步

func animateTwo(){

        UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in
                for lb in self.labelsArray{
                    lb.transform = CGAffineTransformMakeScale(1.5, 1.5)
                }
            }) { (finished) -> Void in
                UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in

                        for lb in self.labelsArray{
                            lb.transform = CGAffineTransformIdentity
                        }

                    }) { (finished) -> Void in

                        if self.refreshControl.refreshing {
                            self.currentLabelIndex = 0
                            self.animateOne()
                        }
                        else {
                            self.isAnimating = false
                            self.currentLabelIndex = 0
                            for var i=0; i<self.labelsArray.count; ++i {
                                self.labelsArray[i].textColor = UIColor.whiteColor()
                                self.labelsArray[i].transform = CGAffineTransformIdentity
                            }
                        }
                }
        }
    }


第二部 , 用for循环给每个label放大1.5倍,最后还原 。原教程用得是写死的数组 ,写了好多行, 说for循环式及时执行的不会有动画效果 。 我这里用for循环是有动画效果的。

还原完成的时候,判断是否还没有刷新好,如果是继续第一个动画 , 如果不是。所有动画属性还原

然后在
scrollViewDidEndDecelerating
方法中调用我们的动画

if refreshControl.refreshing {
            if !isAnimating {
                animateOne()
            }
        }


这个方法是在滚动结束的时候执行。

这时候运行app已经有动画效果了,但是一直不会end 。 我们这里不会从网络上下载数据 。所以用一个计时器去模拟

声明一个计时器
var timer:NSTimer!


func doSomething() {
        timer = NSTimer.scheduledTimerWithTimeInterval(4.0, target: self, selector: "endOfWork", userInfo: nil, repeats: true)
    }

    func endOfWork() {
        refreshControl.endRefreshing()

        timer.invalidate()
        timer = nil
    }


然后在
scrollViewDidEndDecelerating
里面启动这个计时器

if refreshControl.refreshing {
            if !isAnimating {
                doSomething()
                animateOne()
            }
        }


计时结束的时候就会调用
refreshControl.endRefreshing()
结束刷新 ,并停止计时器。

最后效果



当然大家可以奇思妙想 , 想出更多更好的创意 。

下面放上源码:https://github.com/smalldu/SwiftStudy

里面的PullToRefresh
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: