我想实现一个UIScrollView,它可以在按下按钮时上下滚动。我想要的是,当按下按钮时(在按下状态下),滚动视图将继续平滑滚动。当我离开按钮时,滚动应该停止。如何实现此功能?我还附上了我的视图的屏幕快照,其中包含滚动视图和向上/向下箭头按钮。
注意:我想要的是,每当用户按下按钮并持续按住手指时,滚动视图就会继续滚动(除非到达底部)。当他从按钮上离开手指时,滚动应该停止。有什么方法可以实现这种功能?
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)
}
}