UIViewAnimationTransition flip UIImageView - ios

Video
My UIView.transitions in my tapped function at the bottom works the first time but the second time for my else statement to flip back to the front side crashes every time. Getting error message "fatal error: unexpectedly found nil while unwrapping an Optional value". Want to successfully flip front to back and back to front every time :) thanks you in advance pals. ;) Also, I added my ImageOne & ImageTwo views in my storyboard!
import UIKit
import Foundation
import Firebase
import FirebaseDatabase
class ViewController: UIViewController {
#IBOutlet weak var mainScrollView: UIScrollView!
#IBOutlet weak var imageOne: UIImageView!
#IBOutlet weak var imageTwo: UIImageView!
var myImageArray = [UIImage]()
var myImageArray2 = [UIImage]()
var back: UIImageView!
var front: UIImageView!
var showingFront = true
override func viewDidLoad() {
super.viewDidLoad()
SignedIn()
self.view.addGestureRecognizer(revealViewController().panGestureRecognizer())
let singleTap = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapped))
singleTap.numberOfTapsRequired = 1
mainScrollView.addGestureRecognizer(singleTap)
mainScrollView.isUserInteractionEnabled = true
mainScrollView.frame = view.frame
myImageArray = [image1, image2 ,image3, image4, image5]
myImageArray2 = [imageText1, imageText2 ,imageText3, imageText4, imageText5]
for i in 0..<myImageArray.count {
front = UIImageView()
front.image = myImageArray[i]
front.contentMode = .scaleToFill
let yPosition = self.view.frame.height * CGFloat(i) + self.view.frame.height/2 - (self.view.frame.height / 1.1)/2
let xPosition = self.view.frame.width/2 - (self.view.frame.width / 1.1)/2
front.frame = CGRect(x: xPosition, y: yPosition, width: self.view.frame.width / 1.1, height: self.view.frame.height / 1.1)
front.layer.borderWidth = 5
back = UIImageView()
back.image = myImageArray2[i]
back.contentMode = .scaleToFill
back.frame = CGRect(x: xPosition, y: yPosition, width: self.view.frame.width / 1.1, height: self.view.frame.height / 1.1)
back.layer.borderWidth = 5
mainScrollView.contentSize.height = mainScrollView.frame.height * CGFloat(i + 1)
imageOne.addSubview(front)
imageTwo.addSubview(back)
}
}
func tapped() {
print("Hello")
if (showingFront) {
UIView.transition(from: imageOne, to: imageTwo, duration: 1, options: UIViewAnimationOptions.transitionFlipFromRight, completion: nil)
showingFront = false
} else {
UIView.transition(from: imageTwo, to: imageOne, duration: 1, options: UIViewAnimationOptions.transitionFlipFromLeft, completion: nil)
showingFront = true
}
}
}

You need to add a second animation option to keep the "from" view in play. Here's how I do it:
// declare the animation options
let transitionOptions: UIViewAnimationOptions = [.transitionFlipFromRight, .showHideTransitionViews]
func tapped() {
print("Hello")
if (showingFront) {
UIView.transition(from: imageOne, to: imageTwo, duration: 1, options: transitionOptions, completion: nil)
showingFront = false
} else {
UIView.transition(from: imageTwo, to: imageOne, duration: 1, options: transitionOptions, completion: nil)
showingFront = true
}
}
I recall that it took me a solid hour to add a second option, as Swift 2 code you could do it differently.

Related

how to make collapsible/expandable views in swift

I created a collapsible/expandable form on android. please see GIF below
https://giphy.com/gifs/zVvcKtgT9QTaa1O29O
I'm trying to create something similar on ios, so far, i've already created the bottom sheet as seen below
Looking at this GIF https://gfycat.com/dismalbronzeblowfish, you'd notice i'm able to expand and collapse the views, but there's a big gap where the view used to be, the expected behavior is that the space collapses also with an animation
Below is the code for the bottom sheet
class BottomSheetViewController: UIViewController {
// holdView can be UIImageView instead
#IBOutlet weak var holdView: UIView!
#IBOutlet weak var left: UIButton!
#IBOutlet weak var right: UIButton!
#IBOutlet weak var pickupView: UIView!
#IBOutlet weak var deliveryView: UIView!
#IBOutlet weak var deliverydetailsView: UIView!
#IBOutlet weak var pickupDetailsVIew: UIControl!
let fullView: CGFloat = 100
var partialView: CGFloat {
return UIScreen.main.bounds.height - 300
}
override func viewDidLoad() {
super.viewDidLoad()
let gesture = UIPanGestureRecognizer.init(target: self, action: #selector(BottomSheetViewController.panGesture))
view.addGestureRecognizer(gesture)
let pickupTapGesture = UITapGestureRecognizer(target: self, action: #selector(pickupButton))
let deliveryTapGesture = UITapGestureRecognizer(target: self, action: #selector(deliveryButton))
pickupView.addGestureRecognizer(pickupTapGesture)
deliveryView.addGestureRecognizer(deliveryTapGesture)
pickupView.setBorder(radius: 5, color: .black)
deliveryView.setBorder(radius: 5, color: .black)
roundViews()
deliverydetailsView.isHidden = true
pickupDetailsVIew.isHidden = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
prepareBackgroundView()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIView.animate(withDuration: 0.6, animations: { [weak self] in
let frame = self?.view.frame
let yComponent = self?.partialView
self?.view.frame = CGRect(x: 0, y: yComponent!, width: frame!.width, height: frame!.height)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func rightButton(_ sender: AnyObject) {
print("clicked")
}
#objc func pickupButton(_ sender: UITapGestureRecognizer) {
print("tap")
if pickupDetailsVIew.isHidden {
expand(pickupDetailsVIew)
collapse(deliverydetailsView)
} else {
collapse(pickupDetailsVIew)
}
}
#objc func deliveryButton(_ sender: UITapGestureRecognizer) {
print("tap")
if deliverydetailsView.isHidden {
expand(deliverydetailsView)
collapse(pickupDetailsVIew)
} else {
collapse(deliverydetailsView)
// if deliveryView.isHidden && pickupDetailsVIew.isHidden {
//
// }
}
}
func expand(_ view: UIView) {
view.isHidden = false
}
func collapse(_ view: UIView) {
view.isHidden = true
}
// #IBAction func close(_ sender: AnyObject) {
// UIView.animate(withDuration: 0.3, animations: {
// let frame = self.view.frame
// self.view.frame = CGRect(x: 0, y: self.partialView, width: frame.width, height: frame.height)
// })
// }
#objc func panGesture(_ recognizer: UIPanGestureRecognizer) {
let translation = recognizer.translation(in: self.view)
let velocity = recognizer.velocity(in: self.view)
let y = self.view.frame.minY
if ( y + translation.y >= fullView) && (y + translation.y <= partialView ) {
self.view.frame = CGRect(x: 0, y: y + translation.y, width: view.frame.width, height: view.frame.height)
recognizer.setTranslation(CGPoint.zero, in: self.view)
}
if recognizer.state == .ended {
var duration = velocity.y < 0 ? Double((y - fullView) / -velocity.y) : Double((partialView - y) / velocity.y )
duration = duration > 1.3 ? 1 : duration
UIView.animate(withDuration: duration, delay: 0.0, options: [.allowUserInteraction], animations: {
if velocity.y >= 0 {
self.view.frame = CGRect(x: 0, y: self.partialView, width: self.view.frame.width, height: self.view.frame.height)
} else {
self.view.frame = CGRect(x: 0, y: self.fullView, width: self.view.frame.width, height: self.view.frame.height)
}
}, completion: nil)
}
}
func roundViews() {
view.layer.cornerRadius = 5
holdView.layer.cornerRadius = 3
// left.layer.cornerRadius = 10
// right.layer.cornerRadius = 10
// left.layer.borderColor = UIColor(red: 0, green: 148/225, blue: 247.0/255.0, alpha: 1).cgColor
// left.layer.borderWidth = 1
view.clipsToBounds = true
}
func prepareBackgroundView(){
// let blurEffect = UIBlurEffect.init(style: .dark)
// let visualEffect = UIVisualEffectView.init(effect: blurEffect)
// let bluredView = UIVisualEffectView.init(effect: blurEffect)
// bluredView.contentView.addSubview(visualEffect)
//
// visualEffect.frame = UIScreen.main.bounds
// bluredView.frame = UIScreen.main.bounds
//
// view.insertSubview(bluredView, at: 0)
}
}
I need some help/pointers in the right direction from anyone who has done this before, or who knows how to do this
Thank you

iOS Spin UIImageView with deceleration motion at random position

I trying to create a spin wheel which rotate on tap and it rotates for certain period of time and stops at some random circular angle.
import UIKit
class MasterViewController: UIViewController {
lazy var imageView: UIImageView = {
let bounds = self.view.bounds
let v = UIImageView()
v.backgroundColor = .red
v.frame = CGRect(x: 0, y: 0,
width: bounds.width - 100,
height: bounds.width - 100)
v.center = self.view.center
return v
}()
lazy var subView: UIView = {
let v = UIView()
v.backgroundColor = .black
v.frame = CGRect(x: 0, y: 0,
width: 30,
height: 30)
return v
}()
var dateTouchesEnded: Date?
var dateTouchesStarted: Date?
var deltaAngle = CGFloat(0)
var startTransform: CGAffineTransform?
var touchPointStart: CGPoint?
override func viewDidLoad() {
super.viewDidLoad()
self.imageView.addSubview(self.subView)
self.view.addSubview(self.imageView)
self.imageView.isUserInteractionEnabled = true
self.setupGesture()
}
private func setupGesture() {
let gesture = UITapGestureRecognizer(target: self,
action: #selector(handleGesture(_:)))
self.view.addGestureRecognizer(gesture)
}
#objc
func handleGesture(_ sender: UITapGestureRecognizer) {
var timeDelta = 1.0
let _ = Timer.scheduledTimer(withTimeInterval: 0.2,
repeats: true) { (timer) in
if timeDelta < 0 {
timer.invalidate()
} else {
timeDelta -= 0.03
self.spinImage(timeDelta: timeDelta)
}
}
}
func spinImage(timeDelta: Double) {
print("TIME DELTA:", timeDelta)
let direction: Double = 1
let rotation: Double = 1
UIView.animate(withDuration: 5,
delay: 0,
options: .curveEaseOut,
animations: {
let transform = self.imageView.transform.rotated(
by: CGFloat(direction) * CGFloat(rotation) * CGFloat(Double.pi)
)
self.imageView.transform = transform
}, completion: nil)
}
}
I tried via above code, but always stops on initial position
i.e. the initial and final transform is same.
I want it to be random at every time.
One thing you can do is make a counter with a random number within a specified range. When the time fires, call spinImage then decrement the counter. Keep doing that until the counter reaches zero. This random number will give you some variability so that you don't wind up with the same result every time.
#objc func handleGesture(_ sender: UITapGestureRecognizer) {
var counter = Int.random(in: 30...33)
let _ = Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true) { (timer) in
if counter < 0 {
timer.invalidate()
} else {
counter -= 1
self.spinImage()
}
}
}
In spinImage, instead of rotating by CGFloat.pi, rotate by by CGFloat.pi / 2 so that you have four possible outcomes instead of two.
func spinImage() {
UIView.animate(withDuration: 2.5,
delay: 0,
options: .curveEaseOut,
animations: {
let transform = self.imageView.transform.rotated(
by: CGFloat.pi / 2
)
self.imageView.transform = transform
}, completion: nil)
}
You may want to mess around with the counter values, the timer interval, and the animation duration to get the effect that you want. The values I chose here are somewhat arbitrary.

UIScrollview Animation Transition From View To View

I am trying to perform a transition animation whenever a user scrolls on a paginated view, i.e: From Page 1 to Page 2.
Unfortunately, I've not been able to replicate that.
Attach below is what I've done:
class OnboardingParallaxImageView: BaseUIView, UIScrollViewDelegate {
let allImages = [#imageLiteral(resourceName: "onboarding_handshake_icon"), #imageLiteral(resourceName: "onboarding_paylinc_icon")]
var activeCurrentPage = 1
let bgView: UIImageView = {
let image = #imageLiteral(resourceName: "onboard_bg_gradient")
let view = UIImageView(image: image)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let firstImageView: UIImageView = {
let view = UIImageView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let secondImageView: UIImageView = {
let view = UIImageView()
view.isHidden = true
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var firstImageHeightAnchor: NSLayoutConstraint?
var firstImageWidthAnchor: NSLayoutConstraint?
var secondImageHeightAnchor: NSLayoutConstraint?
var secondImageWidthAnchor: NSLayoutConstraint?
override func setupViews() {
super.setupViews()
addSubview(bgView)
addSubview(firstImageView)
addSubview(secondImageView)
bgView.widthAnchor.constraint(equalTo: widthAnchor).isActive = true
bgView.heightAnchor.constraint(equalTo: heightAnchor).isActive = true
bgView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
bgView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
firstImageWidthAnchor = firstImageView.widthAnchor.constraint(equalTo: widthAnchor)
firstImageWidthAnchor?.isActive = true
firstImageHeightAnchor = firstImageView.heightAnchor.constraint(equalTo: heightAnchor)
firstImageHeightAnchor?.isActive = true
firstImageView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
firstImageView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
firstImageView.image = allImages[0]
secondImageWidthAnchor = secondImageView.widthAnchor.constraint(equalTo: widthAnchor)
secondImageWidthAnchor?.isActive = true
secondImageHeightAnchor = secondImageView.heightAnchor.constraint(equalTo: heightAnchor)
secondImageHeightAnchor?.isActive = true
secondImageView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
secondImageView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
secondImageView.image = allImages[1]
}
override func layoutSubviews() {
super.layoutSubviews()
let frameWidth = frame.size.width
secondImageHeightAnchor?.constant = -(frameWidth - 32)
secondImageWidthAnchor?.constant = -(frameWidth - 32)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offSet = scrollView.contentOffset.x
let frameWidth = frame.size.width / 2
let toUseConstant = (CGFloat(abs(offSet)) / frameWidth)
if activeCurrentPage == 1 {
if offSet <= 0 {
firstImageHeightAnchor?.constant = 0
firstImageWidthAnchor?.constant = 0
firstImageView.isHidden = false
secondImageView.isHidden = true
} else {
firstImageHeightAnchor?.constant += -(toUseConstant)
firstImageWidthAnchor?.constant += -(toUseConstant)
firstImageView.isHidden = false
secondImageHeightAnchor?.constant += -(toUseConstant)
secondImageWidthAnchor?.constant += -(toUseConstant)
secondImageView.isHidden = false
secondImageView.alpha = toUseConstant
}
}
UIView.animate(withDuration: 0.5) {
self.layoutSubviews()
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
self.activeCurrentPage = scrollView.currentPage
}
}
This is the result of what I've been able to achieve:
How can I go about transitioning from A to B without any funny behaviour.
Thanks
The easiest way to achieve smooth behaviour is using UIViewPropertyAnimator.
Setup the initial values for each image view:
override func viewDidLoad() {
super.viewDidLoad()
firstImageView.image = // your image
secondImageView.image = // your image
secondImageView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
secondImageView.alpha = 0
}
Then create property animator for each imageView
lazy var firstAnimator: UIViewPropertyAnimator = {
// You can play around with the duration, curve, damping ration, timing
let animator = UIViewPropertyAnimator(duration: 2, curve: .easeIn, animations: {
self.firstImageView.image.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
self.firstImageView.image.alpha = 0
})
return animator
}()
and the second one
lazy var secondAnimator: UIViewPropertyAnimator = {
let animator = UIViewPropertyAnimator(duration: 2, curve: .easeIn, animations: {
self.secondImageView.transform = CGAffineTransform(scaleX: 1, y: 1)
self.secondImageView.alpha = 1
})
return animator
}()
now on scrollViewDidScroll when you have calculated the completed percent just update the animators:
firstAnimator.fractionComplete = calculatedPosition
secondAnimator.fractionComplete = calculatedPosition
You can apply the same approach for multiple views
You might want to consider using a Framework for this instead of reinventing the wheel. Something like Hero for example.
There as some basic examples to get you started. Essentially this provides you an easy to use option to code transition behavior between two UIViewControllers by defining how each UI-Component should behave base on the transition progress.
I have achieved it using the keyframe animation on ImageView's frame. But you can also achieve it using the constraint based animation as you tried. Just replace the frames size variations that I have done here with the change in constraint's constants as per your convenience.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var imgView1: UIImageView! //HANDSHAKE image on TOP
#IBOutlet weak var imgView2: UIImageView! //CREDIT_CARD and PHONE image
#IBOutlet weak var imgView3: UIImageView! //SINGLE_HAND image
let minimumFrameSize = CGSize(width: 0.0, height: 0.0)
let meetingPointFrameSize = CGSize(width: 150.0, height: 150.0)
let maximumFrameSize = CGSize(width: 400.0, height: 400.0)
override func viewDidLoad() {
super.viewDidLoad()
let centerOfImages = CGPoint(x: self.view.frame.width/2 , y: self.view.frame.height/2)
//initial state
self.imgView1.frame.size = maximumFrameSize
self.imgView1.alpha = 1.0
self.imgView2.frame.size = minimumFrameSize
self.imgView2.alpha = 0.0
self.imgView3.frame.size = minimumFrameSize
self.imgView3.alpha = 0.0
self.imgView1.center = centerOfImages
self.imgView2.center = centerOfImages
self.imgView3.center = centerOfImages
UIView.animateKeyframes(withDuration: 5.0, delay: 2.0, options: [UIView.KeyframeAnimationOptions.repeat,
UIView.KeyframeAnimationOptions.calculationModeLinear],
animations: {
UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.25, animations: {
self.imgView1.frame.size = self.meetingPointFrameSize
self.imgView1.alpha = 0.3
self.imgView1.center = centerOfImages
self.imgView2.frame.size = self.meetingPointFrameSize
self.imgView2.alpha = 0.3
self.imgView2.center = centerOfImages
/*image 1 and image 2 meets at certain point where
image 1 is decreasing its size and image 2 is increasing its size simultaneously
*/
})
UIView.addKeyframe(withRelativeStartTime: 0.25, relativeDuration: 0.25, animations: {
self.imgView1.frame.size = self.minimumFrameSize
self.imgView1.alpha = 0.0
self.imgView1.center = centerOfImages
self.imgView2.frame.size = self.maximumFrameSize
self.imgView2.alpha = 1.0
self.imgView2.center = centerOfImages
/* image 1 has decreased its size to zero and
image 2 has increased its size to maximum simultaneously
*/
})
UIView.addKeyframe(withRelativeStartTime: 0.4, relativeDuration: 0.1, animations: {
self.imgView2.frame.size = self.maximumFrameSize
self.imgView2.alpha = 1.0
self.imgView2.center = centerOfImages
/* Hold for a moment
*/
})
UIView.addKeyframe(withRelativeStartTime: 0.6, relativeDuration: 0.15, animations: {
self.imgView2.frame.size = self.meetingPointFrameSize
self.imgView2.alpha = 0.3
self.imgView2.center = centerOfImages
self.imgView3.frame.size = self.meetingPointFrameSize
self.imgView3.alpha = 0.3
self.imgView3.center = centerOfImages
/*image 2 and image 3 meets at certain point where
image 2 is decreasing its size and image 3 is increasing its size simultaneously
*/
})
UIView.addKeyframe(withRelativeStartTime: 0.75, relativeDuration: 0.25, animations: {
self.imgView2.frame.size = self.minimumFrameSize
self.imgView2.alpha = 0.0
self.imgView2.center = centerOfImages
self.imgView3.frame.size = self.maximumFrameSize
self.imgView3.alpha = 1.0
self.imgView3.center = centerOfImages
/* image 2 has decreased its size to zero and
image 3 has increased its size to maximum simultaneously
*/
})
}) { (finished) in
/*If you have any doubt or need more enhancement or in case you need my project. Feel free to ask me.
Please ping me on skype/email:
ojhashubham29#gmail.com
or connect me on Twitter
#hearthackman
*/
}
}
}

UIView.animate with imageArray inside of UIScrollView but with effect like paging enable

I'm new in Swift but I have some basic experience.
I have successfully created an animation with three images and they repeat themselves. But I would like the effect of this repetition to be like when you in attributes inspector of UIScrollView check paging enable.
Inside of options: UIView.AnimationOptions I tried different Constants but I can not find that suits me.
My question: Can I animate image array like you swipe images in scroll view with paging enable?
class ViewController: UIViewController {
#IBOutlet weak var mainScrollView: UIScrollView!
var imageArray = [UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
imageArray = [UIImage(named: "forest")!, UIImage(named: "slika1")!, UIImage(named: "slika2")!]
for i in 0..<imageArray.count {
let imageView = UIImageView()
imageView.image = imageArray[i]
imageView.contentMode = .scaleAspectFit
let xPosition = self.miniView.frame.width * CGFloat(i)
imageView.frame = CGRect(x: xPosition, y: 0, width: self.mainScrollView.frame.width, height: self.mainScrollView.frame.height)
mainScrollView.contentSize.width = mainScrollView.frame.width * CGFloat(i + 1)
mainScrollView.addSubview(imageView)
}
startAnimating()
}
func startAnimating() {
var newOffset = mainScrollView.contentOffset
newOffset.x = 0.0
newOffset.x += mainScrollView.frame.width * CGFloat(imageArray.count - 1)
UIView.animate(withDuration: Double(imageArray.count), delay: 5, options: [.repeat, .allowUserInteraction], animations: {
self.mainScrollView.contentOffset = newOffset
})
}
}
Ok, if i correctly understand what you want, this is the correct answer.
Animate page by page, with a 5 seconds delay with one animation and another.
You need to use Timer.scheduledTimer to trigger method that scroll to the next page. With that solution, you can check paging enable ON, so the user can change the page itself.
I hope it helps
class ViewController: UIViewController {
#IBOutlet weak var mainScrollView: UIScrollView!
var imageArray = [UIImage]()
var currentPage = 0
override func viewDidLoad() {
super.viewDidLoad()
imageArray = [UIImage(named: "forest")!, UIImage(named: "slika1")!, UIImage(named: "slika2")!]
for i in 0..<imageArray.count {
let imageView = UIImageView()
imageView.image = imageArray[i]
imageView.contentMode = .scaleAspectFit
let xPosition = self.miniView.frame.width * CGFloat(i)
imageView.frame = CGRect(x: xPosition, y: 0, width: self.mainScrollView.frame.width, height: self.mainScrollView.frame.height)
mainScrollView.contentSize.width = mainScrollView.frame.width * CGFloat(i + 1)
mainScrollView.addSubview(imageView)
}
Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(startAnimating), userInfo: nil, repeats: true)
}
#objc func startAnimating() {
//that line check if the current page is the last one, and set it to the first, otherwise, it increment the currentPage
self.currentPage = (self.currentPage == imageArray.count-1) ? 0 : self.currentPage+1
var newOffset = mainScrollView.contentOffset
newOffset.x = mainScrollView.frame.width * CGFloat(self.currentPage)
self.mainScrollView.setContentOffset(newOffset, animated: true)
}
}

Starting an action when View Controller Loads

How do I start an action when the view controller loads on screen?
I've managed to do the function I want with an #IBAction but I don't want a button press for the action to happen, I want it to start the action when the page loads
any thoughts?
class ViewController: UIViewController {
var progress: KDCircularProgress!
#IBOutlet weak var Label1: UILabel!
var LabelText = String()
var scorestart = 1.0
var anglepercent = 3.6
override func viewDidLoad() {
super.viewDidLoad()
Label1.text = LabelText
view.backgroundColor = UIColor(white: 0.22, alpha: 1)
progress = KDCircularProgress(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
progress.startAngle = -90
progress.progressThickness = 0.2
progress.trackThickness = 0.3
progress.clockwise = true
progress.gradientRotateSpeed = 10
progress.roundedCorners = false
progress.glowMode = .Forward
progress.glowAmount = 0.9
progress.setColors(UIColor.yellowColor())
progress.center = CGPoint(x: view.center.x, y: view.center.y + 25)
view.addSubview(progress)
}
#IBAction func Animate(sender: AnyObject) {
progress.angle = Double(scorestart * anglepercent)
progress.animateFromAngle(0, toAngle: 270, duration: 2) {
completed in
if completed {
print("animation stopped, completed")
} else {
print("animation stopped, was interrupted")
}
Use :-
Basic idea here is that whenever your view will load corresponding class will look up to viewWillAppear(animated: Bool) function and if it's present in the code it will execute all the code in it.The moment that particular view is about to appear on your UI, your code block in viewWillAppear(animated: Bool) will get called.
class ViewController: UIViewController {
var progress: KDCircularProgress!
#IBOutlet weak var Label1: UILabel!
var LabelText = String()
var scorestart = 1.0
var anglepercent = 3.6
override func viewDidLoad() {
super.viewDidLoad()
Label1.text = LabelText
view.backgroundColor = UIColor(white: 0.22, alpha: 1)
}
override func viewWillAppear(animated :Bool) {
super.viewWillAppear(animated)
progressActn()
//Setting up your progress layer
animateActn()
//Animating that progress layer
}
#IBAction func Animate(sender: AnyObject) {
animateActn()
}
func animateActn(){
progress.angle = Double(scorestart * anglepercent)
progress.animateFromAngle(0, toAngle: 270, duration: 2) {
completed in
if completed {
print("animation stopped, completed")
} else {
print("animation stopped, was interrupted")
}
}
}
func progressActn(){
progress = KDCircularProgress(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
progress.startAngle = -90
progress.progressThickness = 0.2
progress.trackThickness = 0.3
progress.clockwise = true
progress.gradientRotateSpeed = 10
progress.roundedCorners = false
progress.glowMode = .Forward
progress.glowAmount = 0.9
progress.setColors(UIColor.yellowColor())
progress.center = CGPoint(x: view.center.x, y: view.center.y + 25)
view.addSubview(progress)
}
}

Resources