swift 如何在UiScrollView contentOffset Change上运行函数?

vx6bjr1n  于 2023-05-16  发布在  Swift
关注(0)|答案(1)|浏览(103)

我想在“UIScrollView contentOffset.x”(每次滚动)更改上运行一个函数,以便根据我的任务要求动态地进行一些图形更改。

let scroll = UIScrollView.init()
scroll.frame = CGRect(x: 10, y: 10, width: 500, height: 100)
scroll.backgroundColor = .white
scroll.contentSize.width = 1000
scroll.contentSize.height = 100
view.addSubview(scroll)

我想到了两种方法
1)第1种方法(不可用)
喜欢

txtfield.addTarget(self, action: #selector(name_editingchange(_:)), for: UIControlEvents.editingChanged)
"this approach use on textfield "on editingChange""

“addTarget”在scrollview上不起作用,因此我无法使用“UIControlEvents.editingChanged”
2)第二种方法“addGestureRecognizer”(可用)

scroll.scrollview.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(onscroll)))

@objc func onscroll(_ pan:UIPanGestureRecognizer){
    print("on change run func given below")
    taskcompleted()
}

第二种方法有一个问题,当我在滚动视图上使用“PanGesture”时,滚动视图的滚动功能无法恢复滚动功能,通过平移手势我在其功能中编写了一些代码

@objc func onscroll(_ pan:UIPanGestureRecognizer){  

    UIView.animate(withDuration: 0.3) {
        self.scroll.contentOffset.x = self.scroll.contentOffset.x - pan.translation(in: self.view).x
        pan.setTranslation(CGPoint(x: 0, y: 0), in: self.view)
    }

    taskcompleted()
}

但它不像原来的滚动功能那样工作。
我想跑
1)-taskcompleted()func on“UIScrollView contentOffset.x”更改2)-同时完美滚动
我怎么能两者兼顾呢?

jvlzgdj9

jvlzgdj91#

使用UIScrollViewDelegatescrollViewDidScroll()
简单的例子:

class TestViewController: UIViewController, UIScrollViewDelegate {

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        print(scrollView.contentOffset)
        // perform actions as desired based on contentOffset
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let scroll = UIScrollView.init()
        scroll.frame = CGRect(x: 10, y: 10, width: 500, height: 100)
        scroll.backgroundColor = .white
        scroll.contentSize.width = 1000
        scroll.contentSize.height = 100
        view.addSubview(scroll)

        // assign the delegate here
        scroll.delegate = self
    }
}

相关问题