我使用的是UIPageViewController
,我需要得到的ViewController的滚动位置为用户刷卡,所以我可以部分褪色的部分资产,而该视图过渡到下一个UIViewController
。
似乎UIPageViewController
的委托和数据源方法不提供这种任何访问,并在内部我假设UIPageViewController
必须某处使用滚动视图,但它似乎并没有直接继承它,所以我不能打电话
func scrollViewDidScroll(scrollView: UIScrollView) {
}
我已经看到了一些其他职位的建议抢在pageViewController!.view.subviews
的引用,然后第一个指数是一个滚动视图,但是这似乎很哈克。我不知道是否有处理这种更标准的方式。
你可以搜索你的UIPageViewController
内的UIScrollView。要做到这一点,你将不得不实行UIScrollViewDelegate
。
之后,你可以得到你的滚动视图:
for v in pageViewController.view.subviews{
if v.isKindOfClass(UIScrollView){
(v as UIScrollView).delegate = self
}
}
在此之后,您就可以使用所有UIScrollViewDelegate的方法,所以你可以重写scrollViewDidScroll
方法,你可以得到的scrollPosition:
func scrollViewDidScroll(scrollView: UIScrollView) {
//your Code
}
或者,如果你想要一个班轮:
let scrollView = view.subviews.filter { $0 is UIScrollView }.first as! UIScrollView
scrollView.delegate = self
类似基督教的答案,但更多的雨燕样(通过view.subviews不必要继续循环):
for view in self.view.subviews {
if let view = view as? UIScrollView {
view.delegate = self
break
}
}
UIPageViewController滚动不起作用像正常的滚动视图,你不能像其他scrollViews得到scrollView.contentOffset。
所以这里有个窍门让是怎么回事用户滚动时:
首先你必须找到滚动型和委托设为当前的viewController像其他的答案说。
class YourViewController : UIPageViewController {
var startOffset = CGFloat(0) //define this
override func viewDidLoad() {
super.viewDidLoad()
//from other answers
for v in view.subviews{
if v is UIScrollView {
(v as! UIScrollView).delegate = self
}
}
}
.
.
.
}
extension YourViewController : UIScrollViewDelegate{
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
startOffset = scrollView.contentOffset.x
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
var direction = 0 //scroll stopped
if startOffset < scrollView.contentOffset.x {
direction = 1 //going right
}else if startOffset > scrollView.contentOffset.x {
direction = -1 //going left
}
let positionFromStartOfCurrentPage = abs(startOffset - scrollView.contentOffset.x)
let percent = positionFromStartOfCurrentPage / self.view.frame.width
//you can decide what to do with scroll
}
}
var pageViewController: PageViewController? {
didSet {
pageViewController?.dataSource = self
pageViewController?.delegate = self
scrollView?.delegate = self
}
}
lazy var scrollView: UIScrollView? = {
for subview in pageViewController?.view?.subviews ?? [] {
if let scrollView = subview as? UIScrollView {
return scrollView
}
}
return nil
}()
extension BaseFeedViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset.x
let bounds = scrollView.bounds.width
let page = CGFloat(self.currentPage)
let count = CGFloat(viewControllers.count)
let percentage = (offset - bounds + page * bounds) / (count * bounds - bounds)
print(abs(percentage))
}
}