Swift: 以编程方式添加的 ScrollView - 获取此 ScrollView 的当前滚动位置

Swift: Programmatically added ScrollView - Get the current scroll position of this ScrollView

我有这个片段可以将 ScrollView 添加到主视图。例如,如何获取当前滚动位置以移动 header?有人知道解决方案吗?

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.
    }


}

有点不清楚这个问题...如果它滚动了多少...

  1. 让你的控制器服从 UIScrollViewDelegate

  2. 添加以下方法:

func scrollViewDidScroll(_ scrollView: UIScrollView)

  1. 要求滚动查看其偏移量:
  • func scrollViewDidScroll(_ scrollView: UIScrollView) {

    让偏移量 = scrollView.contentOffset.y 如果偏移量{ // 你的逻辑。 } }

谢谢@ingconti 附上我的垂直滚动解决方案:


class ViewController: UINavigationController {
    
    var scrollViewer: UIScrollView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        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 [...]"
        
        let textLable = UILabel(frame: CGRect(x: 0, y: 0, width: 1000, height: 200))
        textLable.text = textData
        
        self.scrollViewer = UIScrollView()
        self.scrollViewer.delegate = self
        self.scrollViewer.contentSize = CGSize(width: textLable.frame.width, height: textLable.frame.height)
        
        scrollViewer.addSubview(textLable)
        view.addSubview(scrollViewer)
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        scrollViewer.frame = view.bounds
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

extension ViewController: UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offset = scrollView.contentOffset.x
        print(offset)
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    }
}