我想知道哪些頁面對用戶可見,並且在檢測到頁面更改時執行特定操作。爲此,我正在使用功能scrollViewDidScroll。由於我沒有得到我想要的結果(什麼都沒有發生),我在stackoverflow上查找了答案,並發現了以下回答的問題:Detecting UIScrollView page change,更確切地說,我使用了Michael Waterfall的答案並將Objective-C代碼快速代碼。檢測y偏移scrollView中的變化並啓用尋呼
下面您會發現我用於在我的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))
}
不,顯然不是,這沒有奏效。 – Moritz