I wanted to implement a UIScrollView that scrolls up and down on button press. What I want is that the scroll view keeps on scrolling smoothly when the button is pressed (in the pressed state). And when I left the button, scrolling should stop. How can I implement this functionality? I have also attached a screenshot of my view that contains scrollview and up/down arrow buttons.
Note: what I want is that whenever user press the button and keeps on holding his finger on it, the scrollview continues to scroll (unless it reaches the bottom end). And when he left his finger from the button, scrolling should stop. Is there any way to implement such functionality?
contentOffset
is what you want. UIScrollView
has such property (and of course its subclasses, the UITableView
and UICollectionView
).
What's a bit tricky in this is how you get to fire up your button while the user hold-press on it. To do this, you would need a long tap gesture recognizer, and a timer. See: Press-and-hold button for "repeat fire"
import UIKit
class ViewController: UITableViewController {
var timer: Timer?
@IBAction func longPressUp(_ sender: UILongPressGestureRecognizer) {
if sender.state == .began {
self.timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.up(_:)), userInfo: nil, repeats: true)
} else if sender.state == .cancelled || sender.state == .ended {
print("CANCELED!")
self.timer?.invalidate()
self.timer = nil
}
}
@IBAction func longPressDown(_ sender: UILongPressGestureRecognizer) {
if sender.state == .began {
self.timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.down(_:)), userInfo: nil, repeats: true)
} else if sender.state == .cancelled || sender.state == .ended {
print("CANCELED!")
self.timer?.invalidate()
self.timer = nil
}
}
@IBAction func up(_ sender: Any) {
print("UP!")
let desiredOffset = CGPoint(x: 0, y: self.tableView.contentOffset.y + 50)
self.tableView.setContentOffset(desiredOffset, animated: true)
}
@IBAction func down(_ sender: Any) {
let desiredOffset = CGPoint(x: 0, y: self.tableView.contentOffset.y - 50)
self.tableView.setContentOffset(desiredOffset, animated: true)
}
}