关于边界的判断,有其他的方法,请留言,总觉得这个边界判断效果不大好......
- 给要拖动的view,添加手势
panView.isUserInteractionEnabled = true
let pan = UIPanGestureRecognizer(target: self, action: #selector(panEvent(gesture: )))
panView.addGestureRecognizer(pan)
- 事件
@objc private func panEvent(gesture: UIPanGestureRecognizer) {
if gesture.state == .began {
print("开始拖动")
}else if gesture.state == .changed || gesture.state == .ended {
if let panView = gesture.view {
// 手势移动的 x和y值随事件变化的总平移量
let translation = gesture.translation(in: panView)
// 左边边界值
if panView.frame.minX <= -0 && translation.x <= 0{
panView.frame = CGRect(x: 0.001, y: panView.frame.minY, width: panView.frame.width, height: panView.frame.height)
return
}
// 右边边界值
if panView.frame.maxX >= (self.width) {
panView.frame = CGRect(x: self.width-panView.frame.width-0.001, y: panView.frame.minY, width: panView.frame.width, height: panView.frame.height)
return
}
// 移动
panView.transform = panView.transform.translatedBy(x: translation.x, y: 0)//translation.y,这里我只变化x值
// 复位,相当于现在是起点
gesture.setTranslation(.zero, in: panView)
// 更新UI的位置
updateUI()
}
}
}