我可以使用scrollView.scrollEnabled
属性来有效启用/禁用滚动。
目前,我在longPressRecognizer
的状态为UIGestureStateBegan
时启用滚动,并在UIGestureStateEnded
时禁用滚动。
当我长按然后拖动手指时,scrollView不会滚动。
我认为滚动视图的panGestureRecognizer
不会得到触摸事件,这很奇怪,因为scrollView
是(我使用touchesBegan,touchesMoved等方法检查)< /强>
答案 0 :(得分:0)
UIScrollView
没有触及,因为在启用UIScrollView上的滚动之前触摸已启动。此示例代码使用UILongPressGestureRecognizer
管理滚动,滚动一个大的UIImageView:
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet var gr: UILongPressGestureRecognizer!
var initialPos = CGPointZero
var dragPos = CGPointZero
// This action is bound to long press gesture recognizer within Interface Builder
@IBAction func longpressHandler(sender: UILongPressGestureRecognizer) {
if sender.state == .Began {
// Save initial position for moving
initialPos = sender.locationInView(scrollView)
}
else if sender.state == .Changed {
// Get new drag location
let loc = sender.locationInView(scrollView)
let newPos = CGPoint(x: initialPos.x - loc.x + dragPos.x, y: initialPos.y - loc.y + dragPos.y)
dragPos = newPos
scrollView.contentOffset = newPos
}
else if sender.state == .Ended {
// Check for end position of the content, snap it back to the edge of the screen if moved too far
var newOffset = scrollView.contentOffset
var move = false
if scrollView.contentOffset.x < 0 {
newOffset.x = 0
move = true
}
if scrollView.contentOffset.y < 0 {
newOffset.y = 0
move = true
}
if scrollView.contentOffset.x > photo.frame.size.width - scrollView.frame.size.width {
newOffset.x = max(self.photo.frame.size.width - self.scrollView.frame.size.width, 0)
move = true
}
if scrollView.contentOffset.y > photo.frame.size.height - scrollView.frame.size.height {
newOffset.y = max(self.photo.frame.size.height - self.scrollView.frame.size.height, 0)
move = true
}
if move {
UIView.animateWithDuration(0.25, animations: {
self.scrollView.contentOffset = newOffset
})
}
}
}
var photo = UIImageView(image: UIImage(named: "photo"))
override func viewDidLoad() {
super.viewDidLoad()
// Set up your scrollview
scrollView.addSubview(photo)
scrollView.contentSize = photo.frame.size
// add the long press gesture recognizer to the scrollview
scrollView.addGestureRecognizer(gr)
}