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