我想知道哪个页面对用户可见,并且在检测到页面发生更改时也会执行某项操作。为此,我使用函数scrollViewDidScroll。由于我没有得到我想要的结果(没有发生),我在stackoverflow上寻找答案并找到了以下问题:Detecting UIScrollView page change,更确切地说,我使用迈克尔瀑布的答案并转换了Objective-C代码快速编写代码。
下面你会找到我在class HomeController: UIViewController, UIScrollViewDelegate {
中创建scrollView的代码。此外,Michael Waterfall的函数在函数initiateScrollView()
中声明并调用。但是,该功能不会打印任何内容。你知道我在做错什么吗?我看不出我犯了什么错误。滚动时没有任何反应(例如从第1页到第2页(homeView
到view2
))。该函数只打印before: 0
一次,之后没有任何反应。
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
initiateScrollView()
}
func initiateScrollView() {
//create scrollView with paging enabled
let scrollView = UIScrollView(frame: view.bounds)
scrollView.isPagingEnabled = true
view.addSubview(scrollView)
//get page size
let pageSize = view.bounds.size
//individual views
let homeView = UIView()
homeView.backgroundColor = .green
let view2 = UIView()
view2.backgroundColor = .blue
let view3 = UIView()
view3.backgroundColor = .red
//array with individual views
let pagesViews = [homeView, view2, view3]
//amount of views
let numberOfPages = pagesViews.count
print(numberOfPages) //prints '3'
//add subviews (pages)
for (pageIndex, page) in pagesViews.enumerated(){
//add individual pages to scrollView
page.frame = CGRect(origin: CGPoint(x:0 , y: CGFloat(pageIndex) * pageSize.height), size: pageSize)
scrollView.addSubview(page)
}
func scrollViewDidScroll(scrollView: UIScrollView) {
var previousPage = 0
let fractionalPage: Float = Float(scrollView.contentOffset.y / pageSize.height)
let page = lround(Double(fractionalPage))
print("before:", page) //prints 'before: 0' once
if previousPage != page {
// Page has changed, do your thing!
// ...
// Finally, update previous page
print("before:", page)
previousPage = page
print("after:", page)
} //never prints anything
}
scrollViewDidScroll(scrollView: scrollView)
//define size of scrollView
scrollView.contentSize = CGSize(width: pageSize.width, height: pageSize.height * CGFloat(numberOfPages))
}
答案 0 :(得分:1)
您忘记将viewController设置为滚动视图的委托,如下所示:
func initiateScrollView() {
//create scrollView with paging enabled
let scrollView = UIScrollView(frame: view.bounds)
scrollView.isPagingEnabled = true
scrollView.delegate = self
view.addSubview(scrollView)
(...) }
我建议您使用scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView)
功能,而不是scrollViewDidScroll(...)
答案 1 :(得分:0)
这是因为您尚未设置scrollview的delegate属性。
在launchScrollView方法中添加scrollView.delegate = self
。