Swift: Programmatically added ScrollView - Get the current scroll position of this ScrollView
I have this snippet to add a ScrollView to the main view. How can I get the current scroll position to move a header for example? Does anyone know a solution?
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
var scrollView: UIScrollView!
let textData: String = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud [...]"
override func viewDidLoad() {
super.viewDidLoad()
let textLable = UILabel(frame: CGRect(x: 0, y: 0, width: 1000, height: 200))
textLable.text = textData
self.scrollView = UIScrollView()
self.scrollView.delegate = self
self.scrollView.contentSize = CGSize(width: textLable.frame.width, height: textLable.frame.height)
scrollView.addSubview(textLable)
view.addSubview(scrollView)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.frame = view.bounds
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Solution 1:
A bit unclear the question... if about how much it scrolled...
-
make your controller obey to UIScrollViewDelegate
-
add the following method:
func scrollViewDidScroll(_ scrollView: UIScrollView)
- ask to scrollview its offset:
-
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset.y if offset{ // Your logic. } }