UIScrollView分页与动画完成处理程序

时间:2015-10-29 21:11:46

标签: ios swift uiscrollview scroll-paging

我有一个带有按钮的UIScrollview,我用它来左右分页:

@IBAction func leftPressed(sender: AnyObject) {

    self.scrollView!.setContentOffset(CGPointMake(0, 0), animated: true)
} 

我想在scrollview完成分页动画后执行一个动作。类似的东西:

@IBAction func leftPressed(sender: AnyObject) {

    self.scrollView!.setContentOffset(CGPointMake(0, 0), animated: true)

    secondFunction()
}

上面的代码不起作用,因为第二个函数在完成scrollview动画化偏移之前运行。我最初的反应是使用完成处理程序,但我不知道如何将一个应用于setContentOffset函数。我试过了:

func animatePaging(completion: () -> Void) {

    self.mainScrollView!.setContentOffset(CGPointMake(0, 0), animated: true)

    completion()
}

通过电话

animatePaging(completion: self.secondFunction())

但是我收到错误“无法使用'(completion())'类型的参数列表调用'animatePaging'。有什么想法吗?

2 个答案:

答案 0 :(得分:4)

问题是你需要一个滚动动画本身的完成处理程序。但是setContentOffset(_:animated:)没有完成处理程序。

一种解决方案是使用UIView的静态函数animateWithDuration(_:animations:completion:)自行设置滚动动画。该函数有一个可以使用的完成处理程序:

UIView.animateWithDuration(0.5, animations: { () -> Void in
        self.scrollView.contentOffset = CGPointMake(0, 0)
    }) { (finished) -> Void in
        self.secondFunction()
    }

答案 1 :(得分:0)

从joern答案更新-Swift 4.2

UIView.animate(withDuration: 0.5, animations: { [unowned self] in
   self.scrollView.contentOffset = .zero
}) { [unowned self] _ in
   self.secondFunction()
}