Answer is having both ways to do so using a
PanGesture
and automatically using aTimer
.
1. Using UIPanGestureRecognizer:
You can achieve this using UIPanGestureRecognizer
. circleView
is your mainView
and nob
is another view
or imageView
which will move outside the circleView
panGesture = UIPanGestureRecognizer(target: self, action: #selector(panHandler(_:)))
nob.addGestureRecognizer(panGesture)
Definition of panHandler(_ :)
@objc func panHandler(_ gesture: UIPanGestureRecognizer) {
let point = gesture.location(in: self)
updateForPoints(point)
}
And here is the core logic how will it work.
func updateForPoints(_ point: CGPoint) {
/*
* Parametric equation of circle
* x = a + r cos t
* y = b + r sin t
* a, b are center of circle
* t (theta) is angle
* x and y will be points which are on circumference of circle
*
270
|
_ | _
|
180 -------o------- 360
|
+ | +
|
90
*
*/
let centerOffset = CGPoint(x: point.x - circleView.frame.midX, y: point.y - circleView.frame.midY)
let a: CGFloat = circleView.center.x
let b: CGFloat = circleView.center.y
let r: CGFloat = circleView.layer.cornerRadius - 2.5
let theta: CGFloat = atan2(centerOffset.y, centerOffset.x)
let newPoints = CGPoint(x: a + r * cos(theta), y: b + r * sin(theta))
var rect = nob.frame
rect.origin = newPoints
nob.center = newPoints
}
2. Automatically move using Timer
let totalSeconds: Int = 30 // You can change it whatever you want
var currentSecond: Int = 1
var timer: Timer?
func degreesToRadians(_ degree: CGFloat) -> CGFloat {
/// Will convert the degree (180°) to radians (3.14)
return degree * .pi / 180
}
func angleFromSeconds(_ seconds: Int) -> CGFloat {
/// Will calculate the angle for given seconds
let aSliceAngle = 360.0 / CGFloat(totalSeconds)
let angle = aSliceAngle * CGFloat(seconds) - 90
return angle
}
/// ------------- TIMER METHODS ------------- ///
func startTimer() {
stopTimer()
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timeDidUpdate(_ :)), userInfo: nil, repeats: true)
timeDidUpdate(timer!)
}
func stopTimer() {
currentSecond = 1
timer?.invalidate()
timer = nil
}
@objc func timeDidUpdate(_ t: Timer) {
let angle = angleFromSeconds(currentSecond)
let theta = degreesToRadians(angle)
updateAngle(theta: theta, animated: true)
currentSecond += 1
if currentSecond > totalSeconds {
self.stopTimer()
}
}
/// --------------- MAIN METHOD -------------- ///
func updateAngle(theta: CGFloat, animated: Bool) {
let a: CGFloat = circleView.center.x
let b: CGFloat = circleView.center.y
let r: CGFloat = circleView.layer.cornerRadius
let newPoints = CGPoint(x: a + r * cos(theta), y: b + r * sin(theta))
var rect = nob.frame
rect.origin = newPoints
if animated {
UIView.animate(withDuration: 0.1, animations: {
self.nob.center = newPoints
/// Uncomment if your nob is not a circle and you want to maintain the angle too
// self.nob.transform = CGAffineTransform.identity.rotated(by: theta)
})
}
else {
nob.center = newPoints
/// Uncomment if your nob is not a circle and you want to maintain the angle too
//nob.transform = CGAffineTransform.identity.rotated(by: theta)
}
}
If I understand you correctly, you want to have nice animated progress indicator. There is of course lot of ways how to achiev that. I am going to provide you little bit complex solution, what will give you full control about animation - change speed during animation, starting from different point, pause at any time, or even revert the animation.
1) Let start with full working example. We need few properties:
class ViewController: UIViewController {
var displayLink:CADisplayLink?
var circlePathLayer = CAShapeLayer()
var dottedLine = CAShapeLayer()
var beginTime:TimeInterval?
2) Define display link. It is pretty fast trigger, what sending event on each display refresh - ie 60 times per second, it can be set manually and this progress func will handle the correct state of your progress view
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .blue
beginTime = Date().timeIntervalSinceReferenceDate
displayLink = CADisplayLink(target: self, selector: #selector(progress))
displayLink?.add(to: RunLoop.main, forMode: .defaultRunLoopMode)
3) Define your circle path, what should be followed
let path = UIBezierPath(arcCenter: view.center, radius: view.center.x - 20, startAngle: -CGFloat.pi / 2, endAngle: CGFloat.pi * 2 - CGFloat.pi / 2, clockwise: true)
4) Define dotted line and default animation for the line. There is timeOffset
, speed
and beginTime
properties what follows CAMediaTimming protocol, and we don't want to animate anything yet, and set the drawing of this layer to the zero - begining state
dottedLine.timeOffset = 0
dottedLine.speed = 0
dottedLine.duration = 1
dottedLine.beginTime = dottedLine.convertTime(CACurrentMediaTime(), from: nil)
dottedLine.repeatCount = 1
dottedLine.autoreverses = false
dottedLine.fillColor = nil
dottedLine.fillMode = kCAFillModeBoth
dottedLine.strokeStart = 0.0
dottedLine.strokeColor = UIColor.white.cgColor
dottedLine.lineWidth = 5.0
dottedLine.lineJoin = kCALineJoinMiter
dottedLine.lineDashPattern = [10,10]
dottedLine.lineDashPhase = 3.0
dottedLine.path = path.cgPath
let pathAnimation = CAKeyframeAnimation(keyPath: "strokeEnd")
pathAnimation.duration = 1
pathAnimation.isRemovedOnCompletion = false
pathAnimation.autoreverses = true
pathAnimation.values = [0, 1]
pathAnimation.fillMode = kCAFillModeBoth
dottedLine.add(pathAnimation, forKey: "strokeEnd")
view.layer.addSublayer(dottedLine)
5) Same for small circle
let circlePath = UIBezierPath(arcCenter: CGPoint(x: 0, y: 0), radius: 10, startAngle: 0, endAngle:CGFloat.pi * 2, clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
shapeLayer.fillColor = UIColor.white.cgColor
shapeLayer.strokeColor = nil
circlePathLayer.addSublayer(shapeLayer)
circlePathLayer.timeOffset = 0
circlePathLayer.speed = 0
circlePathLayer.beginTime = circlePathLayer.convertTime(CACurrentMediaTime(), from: nil)
circlePathLayer.duration = 1
circlePathLayer.repeatCount = 1
circlePathLayer.autoreverses = false
circlePathLayer.fillColor = nil
view.layer.addSublayer(circlePathLayer)
let circleAnimation = CAKeyframeAnimation(keyPath: "position")
circleAnimation.duration = 1
circleAnimation.isRemovedOnCompletion = false
circleAnimation.autoreverses = false
circleAnimation.values = [0, 1]
circleAnimation.fillMode = kCAFillModeBoth
circleAnimation.path = path.cgPath
circlePathLayer.add(circleAnimation, forKey: "position")
}
6) Finally the progress function, it is called very often and at this point you going to set progress position - in my example is set to 30 seconds, but you can add here some conditions to do not change time offset - pause, or change it with different amount to handle the speed, or put it back.
@objc func progress() {
let time = Date().timeIntervalSinceReferenceDate - (beginTime ?? 0)
circlePathLayer.timeOffset = time / 30
dottedLine.timeOffset = time / 30
}
7) As soon as you will finish your animations, do not forget to release resources and invalidate display link
displayLink?.invalidate()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.