Assume I have a couple of buttons. Whenever the user touches (and holds) one of the buttons an associated scroll view is scrolling up, down, left or right. It stops scrolling when the user releases the button or the end of the content is reached.
How can I make this scrolling smooth? Or better what is the best method?
I came up with a couple of ideas:
- call setContentOffset:animated: and call it repeatedly
- install a timer changing the content offset in small time intervals
Both proposals I do not like. The first one is not continuous, the second one is a bit over the top. Are there alternatives?
I tested the following, works well:
- create a timer as a property in the ViewController.
var timer: Timer?
- Trigger it in buttonDown
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(scrollTheView), userInfo: nil, repeats: true)
and invalidate in buttonUp
timer?.invalidate()
scrollTheView would scroll (+ for scroll up):
@objc func scrollTheView() {
scrollView.contentOffset.y += 10 // adjust the increment as needed
}
Credit: https://stackoverflow.com/questions/34235903/press-and-hold-button-for-repeat-fire