这是我到目前为止编写的代码,用于在拖动时更改视图的位置。
当UIPanGestureRecognizer
被更改或开始时,视图会改变其中心点,当我放开手势时,视图就会发生。我不要那个。我希望它跟我的拖动一样Notification Center and Control Center does
。
提前感谢您的帮助。
class ViewController: UIViewController {
let maxY = UIScreen.main.bounds.height
lazy var slideUpView: UIView = {
let view = UIView(frame: CGRect(x: 0, y: maxY - 295, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height / 3 ))
view.backgroundColor = .green
return view
}()
lazy var redImageView: UIView = {
let view = UIView(frame: CGRect(x: 0, y: maxY - 295, width: UIScreen.main.bounds.width, height: slideUpView.frame.height / 2 ))
view.backgroundColor = .red
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
print("MaxX: \(UIScreen.main.bounds.maxX)")
print("Max Hight: \(UIScreen.main.bounds.height)")
print("MaxY: \(UIScreen.main.bounds.maxY)")
print("Max width: \(UIScreen.main.bounds.width)")
// MARK: add the views as subview
let viewsArray = [slideUpView, redImageView]
viewsArray.forEach{view.addSubview($0)}
// Add a UIPanGestureRecognizer to it
viewsArray.forEach {createPanGestureRecognizer(targetView: $0)}
}
// The Pan Gesture
func createPanGestureRecognizer(targetView: UIView) {
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(recognizer:)))
panGesture.maximumNumberOfTouches = 1
targetView.addGestureRecognizer(panGesture)
}
@objc func handlePanGesture(recognizer: UIPanGestureRecognizer) {
if recognizer.state == UIGestureRecognizerState.began || recognizer.state == UIGestureRecognizerState.changed {
let translation = recognizer.translation(in: self.view)
print(recognizer.view!.center.y)
let newPos = CGPoint(x:recognizer.view!.center.x + translation.x, y: recognizer.view!.center.y + translation.y)
if insideDraggableArea(newPos) {
guard let targetedView = recognizer.view else {
print("Error: No View to handle")
return
}
targetedView.center.y = newPos.y
recognizer.setTranslation(.zero, in: targetedView)
}
}
}
private func insideDraggableArea(_ point : CGPoint) -> Bool {
return // point.x > 50 && point.x < 200 &&
point.y > (maxY * 0.27) && point.y <= maxY
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let position = touch.location(in: view)
print(position)
}
}
}
答案 0 :(得分:1)
此代码工作正常。问题发生在我昨天使用的模拟器中。一切都按照我想要的方式在iPhone上进行测试。
答案 1 :(得分:0)
至少在操场上的原型中,我也遇到了这个问题。
我将所有转换(您处于更改后的状态)放入我在handlePanGesture函数中定义的UIViewProperty动画制作器中,然后在开始/更改状态下调用.startAnimation()。
需要对动画进行一些调整,但对我来说却更加流畅。