简体   繁体   English

(快速4)使用UIPanGestureRecognizer旋转视图但位置错误

[英](Swift 4)Use UIPanGestureRecognizer rotate a view but in wrong position

I have a container UIView and a button at right top of container, when I rotate button, I want to make container rotate by angle. 我有一个容器UIView和一个位于容器右上方的按钮,当我旋转按钮时,我想使容器按角度旋转。 But the code not work correctly just rotate fastly. 但是代码不能正常工作,只是旋转很快。

   @objc func btnRotatePanAction(sender: UIPanGestureRecognizer) {
    switch sender.state {
    case .began:
        origin = sender.location(in: self)
        break
    case .changed:
        let second = sender.location(in: self)
        let dx = second.x - origin.x
        let dy = second.y - origin.y
        let radians = atan2(dy, dx); // get bearing in radians
        print("rads: \(radians)")
        container.transform = container.transform.rotated(by: CGFloat(radians))
        origin = second
        break
    case .ended:
        break
    default: break

    }
}

Log output like this: 日志输出如下:

rads: 1.69022525281324 弧度:1.69022525281324

rads: 0.519146114246523 弧度:0.519146114246523

rads: 0.643501108793284 弧度:0.643501108793284

Do you transform the same view, which you applied UIPanGestureRecognizer to? 您是否转换了将UIPanGestureRecognizer应用于的同一视图? It seems that you after transform coordinate system is also changed according to this transform and it changes every time btnRotatePanAction(_:) called. 看来变换后的坐标系也根据此变换而改变,并且每次调用btnRotatePanAction(_:)时它都会改变。 That's why everythings turn around rapidly (and randomly I guess). 这就是为什么一切都会快速转变的原因(我猜是随机的)。

You can add a subview to view which handles UIPanGestureRecognizer and transform subview not main view. 您可以向处理UIPanGestureRecognizer的视图添加子视图,并转换不是主视图的子视图。

And by the way, instead of saving origin position of tap you can just use sender.translation(in: sender.view!) which returns how touch is changed in coordinate system. 顺便说一句,您可以仅使用sender.translation(in: sender.view!)而不是保存水龙头的原点位置,它返回在坐标系中如何改变触摸。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM