-2

enter image description hereThere is a clock image that has a needle for hour and a minute needle and I want to move that needle with hand in a circle. I am new in iOS development so please help me.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
shubham.kaushik
  • 117
  • 1
  • 1
  • 8

1 Answers1

0

That's my solution...
Use the viewNeedle and rotate it around a new pivot point. I've used an estension taken elsewhere here on StackOverflow. Add the needle view on the clock view (made in the storyboard in my example). Add a pan gesture to the view, calculate the angle (given in radiants) between the touch point and the centre of the clock view. Then simply rotate the needle view.

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
    }
}
DungeonDev
  • 1,176
  • 1
  • 12
  • 16