【问题标题】:How to run a function on UiScrollView contentOffset Change?如何在 UiScrollView contentOffset Change 上运行函数?
【发布时间】:2019-10-19 22:19:45
【问题描述】:

我想在“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) 第一种方法(不可用)

喜欢

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

'addTarget' 在滚动视图上不起作用,所以我不能使用'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)- "UIScrollView contentOffset.x" 上的 taskcompleted() 函数更改 2)- 同时完美滚动

我怎样才能做到这两点?

【问题讨论】:

标签: swift scroll uiscrollview programmatically contentoffset


【解决方案1】:

使用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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    相关资源
    最近更新 更多