触摸图像视图并在固定位置绕圈移动

时间:2018-12-17 06:59:23

标签: ios

enter image description here有一个时钟图像,其中有一个小时针和一个分钟针,我想用手将其移动一圈。我是iOS开发的新手,请帮助我。

1 个答案:

答案 0 :(得分:0)

那是我的解决方法...
使用viewNeedle并将其围绕新的枢轴点旋转。我已经在StackOverflow上的其他地方使用了扩展功能。 将指针视图添加到时钟视图(在我的示例中的情节提要中进行)。 向视图添加平移手势,计算触摸点和时钟视图中心之间的角度(以辐射度为单位)。 然后只需旋转针视图即可。

import UIKit

    class ViewController: UIViewController {

    @IBOutlet weak var viewClock: UIView!
    @IBOutlet weak var viewNeedle: UIView!

    var panGestureRecognizer:UIPanGestureRecognizer?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(didPan(sender:)))
        viewNeedle.isUserInteractionEnabled = true
        viewNeedle.addGestureRecognizer(panGestureRecognizer!)
        viewNeedle.setAnchorPoint(CGPoint(x: 0.5, y: 1))
    }

    @objc func didPan(sender: UIPanGestureRecognizer) {
        let location = sender.location(in: view)
        let center = viewClock.center
        let deltaY = location.y - center.y
        let deltaX = location.x - center.x
        let angle = Double(atan2(deltaY, deltaX)) + Double.pi/2
        viewNeedle.transform = CGAffineTransform(rotationAngle: CGFloat(angle))
    }
}

 extension UIView {
     func setAnchorPoint(_ point: CGPoint) {
        var newPoint = CGPoint(x: bounds.size.width * point.x, y: bounds.size.height * point.y)
        var oldPoint = CGPoint(x: bounds.size.width * layer.anchorPoint.x, y: bounds.size.height * layer.anchorPoint.y);

        newPoint = newPoint.applying(transform)
        oldPoint = oldPoint.applying(transform)

        var position = layer.position

        position.x -= oldPoint.x
        position.x += newPoint.x

        position.y -= oldPoint.y
        position.y += newPoint.y

        layer.position = position
        layer.anchorPoint = point
    }
}