Swift create circle progress bar

Swift create circle progress bar DEFAULT

UICircularProgressRing

UICircularProgress ring is a library for rendering circular progress rings and timers.

  • Declarative: Written using SwiftUI (legacy UIKit version available), UICircularProgressRing is declarative making it easy to read, and easy to use.
  • Customizable: Designed to be used in production, all of the views are highly customizable without giving up ease of use. This allows the developer to tailor the look, feel and functionality to fit their needs.
  • Tested: Battle tested in many production applications. UICircularProgressRing is also fully unit tested as well as snapshot tested so developers can feel safe.
  • Documented: UICircularProgressRing's public API is 100% documented and its something that is enforced before any code is ever added. This is a resource that will help any new user understand how to get the most out of this library.

iOS 14+ Note

Since Apple has now added a built in ProgressView the need for this library is about to be over. My recommendation: If you can support iOS 14.0 and use the new system then you should use that. This library will be continued to be maintained (critical bugs will be fixed, etc) but no new features are planned as we are reaching EOL for this library.

Installation

UICircularProgressRing is available in two major versions. The latest version v7.0+ or legacy versions. The legacy version is written using UIKit and requires a deployment target of or . The latest version is written in SwiftUI and requires , , or .

For legacy installation, follow these instructions.

Swift Package Manager

Simply add this library to your package manifest or follow instructions on adding a package dependency using Xcode here.

.package( url: "https://github.com/luispadron/UICircularProgressRing.git", .branch("master") )

Documentation

This projects public API is 100% documented and it's something we spend a lot of time working on. Please make sure to read the documentation before opening any issues, questions, etc.

Read the documentation

Usage

ProgressRing

is a view designed to display some kind of progress, this can be anything which is represented as a percentage in the range . A percentage is represented in decimal format, i.e. is . Progress may be a downloading operation, the grade percentage of a users test score, etc. A short example of using is shown below, for more details read the docs or play with the example app.

structProgressRingExample: View { @Statevar progress = RingProgress.percent(0.44) var body: some View { VStack { ProgressRing( progress: $progress, axis: .top, clockwise: true, outerRingStyle: .init( color: .color(.gray), strokeStyle: .init(lineWidth: 20) ), innerRingStyle: .init( color: .color(.green), strokeStyle: .init(lineWidth: 10), padding: 5 ) ) .animation(.easeInOut(duration: 5)) .padding(32) } } }

An example image of a ProgressRing view rendered with a green inner circle, a gray outer circle and at 44 percent completion.

TimerRing

is a view designed to display time. You initialize the timer by giving it a unit of time and duration, for example: . This means the will run for 60 seconds, filling up the inner ring until finally reaching 100% around the entire outer ring. A short example of using is shown below, for more details read the docs or play with the example app.

structTimerRingExample: View { @Statevar isPaused [email protected] isDone =falsevar body: some View { TimerRing( time: .minutes(1), delay: .seconds(0.5), innerRingStyle: .init( color: .color(.green), strokeStyle: .init(lineWidth: 16), padding: 8 ), isPaused: $isTimerPaused, isDone: $isTimerDone ) { currentTime inText(timeFormatter.string(from: currentTime)) .font(.title) .bold() } } }

A demo image of a timer ring view with a green inner ring, a gray outer ring and at twenty-seven seconds.

Examples

Apps Using UICircularProgressRing

Sours: https://github.com/luispadron/UICircularProgressRing

Circular Progress Bar in iOS

It is really difficult for a beginner to implement a circular progress bar in iOS. So for the guys and gals heres the punch

Anyone can easily make a circular progress bar for an iOS app by simply dragging and dropping. All you need to do is download this to your target.

Once you have added the file in your project and added it to target build all you need to do is this.

Step 1:- Drag the generic UIView to the storyboard.

Step 2:- Make it an instance of a custom class in the identity inspector as shown below.

Step 3:- Connect it to code using control drag.

Step 4:- You can now use any of the public functions and variables of the Circular Progress Bar.

Step 5:- Done

The CircularProgressBar.swift file is also embedded below. Have a look at it.

I am also planning to make more of these light weight modular UIViews. Follow me for more such articles. Also if you like it or you are planning to use it clap for this article and I will know you loved it !!

If you are interested in knowing how to make them yourself please let me know in a reply to this article below.

Follow me on GitHub, Instagram, Facebook, WordPress and Medium.

Sours: https://codeburst.io/circular-progress-bar-in-ios-d06629700334
  1. Fitbit helpline
  2. Cell depot usa
  3. Honda snowblower parts
  4. Gtx 1070 price
  5. Joseph clyde daniels

Circular Progress Indicator in Swift

Updated on April 17, 2017 – Swift 3

Circular progress indicators are a nice and compact way to visualize progress information for users of your iOS app. I was extremely grateful to come across Kaan Dedeoglu’s KDCircularProgress project on GitHub. It’s a versatile little UI component written in Swift that provides a great amount of flexibility and customization options. I love it!

As a bonus to this amazing component, recent contributions by Kaan have opened up the ability for us to lay out and set up the circular progress indicator in the Storyboard!

My goal in this article is to help get you up and running with this library in your own Storyboard-based Swift project.

Example project

Kaan’s GitHub repository has an example project, but I’ve also gone ahead and made one as well for showing how to use this indicator in a Storyboard. We’ll be using the example I created as a reference point for the forthcoming walk-through.

Circular Progress Example

Getting started

The most obvious starting place is to head over to the KDCircularProgress repository on GitHub to grab the KDCircularProgress.swift source file and add it to your own Swift project. Kaan has things set up with CocoaPods as well if you care to use that. I found adding the .swift file to my project to be the least intrusive way to add this indicator to my UI components arsenal.

To the Storyboard!

Since Kaan added and support, working with the circular progress indicator in the Storyboard is super easy.

To get started, all you need to do is drag a plain View over to the Storyboard Scene. Set up your constraints to correctly position the view where you need it:

UIView with Constraints

Next, you need to set the View’s class to a custom class, namely, :

Set View Class

With that in place, Xcode will process things and allow you to modify the properties of the progress indicator directly in the attributes section of the Utilities pane. Best of all, you’ll see those changes be reflected in the Storyboard scene in real-time as you adjust values!

Customized in Storyboard

viewDidLoad()

While in the Storyboard, I set a few values so that I could actually see certain colors when progress had been made. However, to get things set to their true initial state, there may be some values you want to reset in . For example, I set the property to 90 degrees so that I could see the color of the progress track in the storyboard. But when I load the app, I want the angle to be 0 degrees (since no progress has been made when the app first loads).

To accomplish this, you’d simply make sure there’s an outlet between your progress view in the Storyboard and the View Controller. Once they’re connected, you can write something as simple as to start off with no progress.

Increasing progress

We’re dealing with a progress indicator here, so this implies that there’s a beginning, some incremental steps taken toward a completion goal, and of course, the fully completed whatever it was you were doing.

The example I’ve contrived is a simple counter with an upper limit of 5. So as you tap “Increase Progress”, the circular progress view should update to be some fraction of the way around the 360 degree circle based upon how close we are to completing the count to 5.

There’s a function I’ve built to calculate the new angle:

The rest is simply a matter of updating the current count and animating to the new angle:

Resetting the indicator

To reset everything, we’d want to update the state of our current count back to 0.

The change to the circular progress indicator’s visualization of the progress state can be animated by calling the view’s method:

Wrapping up

There are a ton of other customization options that you can play with. I highly recommend this UI component if you’re looking for an easy-to-use, versatile circular progress indicator!

comments powered by
Sours: https://www.andrewcbancroft.com/2015/07/09/circular-progress-indicator-in-swift/
Swift Animations - Activity Ring Animation (Swift 5, Xcode 12, Beginner) - iOS Development 2021

Archives

In this tutorial we’re going to learn how to design and build a circular progress bar in SwiftUI using stacks, Circle shapes and view modifiers. The sample app will include a circular progress bar and a button underneath it, which will increment the progress.

The final product will look like this:

Circular progress bar in SwiftUI

Start by creating a new single view iOS app using SwiftUI.

Design/Architecture considerations

  • Just like in a UIProgressView, our current progress value will be represented by a Float which can have values between 0.0 and 1.0 (inclusive). It will simplify the math later on in the tutorial.
  • If you set the current progress value to anything above 1.0, the progress bar will treat it as 1.0 (or 100%) and won’t extend beyond its bounds.
  • The container/parent view will manage the state of progress bar (e.g., its current value).
  • The increment button will increase the current progress value by a random value.

Prepare ContentView

First of all, add a progressValue @State variable to the ContentView which will correspond to the progress value displayed by the progress bar.

Then, make sure that the body of ContentView is a ZStack and change the background color of main view to make it look nicer. Finally, make sure that the background color spreads across the entire screen by applying the edgesIgnoringSafeArea(.all) modifier.

There is nothing exciting to see yet, but the result should look like this:

App background using edgesIgnoringSafeArea(.all) modifier

Start building ProgressBar view

Start by creating empty ProgressBar view with a reference to its current progress value binding and one circle reflecting background of the progress bar. Style the first circle by applying desired stroke width, opacity and color:

Use the new ProgressBar view in the body of ContentView by wrapping it in a VStack and using Spacer() to push it to the top of the screen. Use the frame() modifier to fix the size of the progress bar and apply some padding to move it away from screen edges:

Pay special attention to the following line which passes a reference to the progressValue binding from ContentView to the ProgressBar view:

The result should look like this:

Background of progress bar

Indicate progress on the circle

The progress on the circle will be indicated by layering another circle (with darker color) on top of the background circle we just created. We’ll refer to this circle a progress circle. That’s why we used a ZStack earlier when creating the ProgressBar view – it will allow us to place one Circle above another and create an impression of progress bar.

In order to only render a part of the progress circle (to represent a percentage/fraction), we’re going to use the trim() modifier on the Circle shape which trims a shape by a fractional amount.

Add a second Circle to the ZStack of ProgressBar with fixed trim value for now (to indicated 30% progress) and rounded stroke line on both sides:

The result should look like that:

Initial progress bar

Fantastic! We’re getting closer to what we want to achieve however there are several things we need to fix right now:

  • We have hardcoded the trim value to 0.3 (or 30%) but we need to make it refer to the actual progress value variable and prevent it from going over 1.0 (or 100%).
  • Personally, I’d like the progress indicator to start at the top of the progress circle and not on the right hand side (which is default).
  • We need to add an animation to the progress circle to create an appearance of smooth progression when progress value is updating.

Let’s tackle the above points one by one.

Point progress circle at its progress value variable

Update the trim() modifier parameters to trim the progress circle from 0.0 to self.progress. The stroke() and foregroundColor() modifiers stay the same:

In order to prevent the trim from wrapping around and going over 1.0 (or 100%) we need to place a constraint on its end value. We’ll achieve it by applying the following formula:

In other words, we’re going to pick current progress value as long as it’s less than 1.0. If for some reason it’s higher than 1.0, then we’ll cap it at 1.0 by applying the min() function. Update your trim() modifier with the above code.

Start progress indicator at the top of the progress circle

All we need to do is to rotate the progress circle by 270 degrees in order to align its origin with the top. Add the rotationEffect() modifier to the progress circle:


Animate the progress circle

Animations in SwiftUI can be as simple as applying the animation() modifier with desired animation type. The complete progress circle should look like that:


Add a percentage text label in the middle of progress bar

Add a new Text view to the ZStack of the ProgressBar view:

The text view will display the current progress value (no larger than 1.0) and multiply it by a 100 to indicate a percentage. The String format modifier will round the current progress value to zero decimal places.

Complete ProgressBar view

To sum it all up, the ProgressBar view should look like this:

If you’d like to see it in action, hardcode the progressValue inside of the ContentView to a desired value (e.g., 0.28):

The result should look like this:

Progress bar in SwiftUI

Revert the progressValue back to 0.0.

Add increment button to control the progress bar

For testing purposes, we’re going to add a button to the ContentView, inside of its VStack, just below the ProgressBar() view. The button will call the incrementProgress() method which picks a random value from an array of possible progress values and updates the progressValue variable.

Complete code for the project

Final result:

Circular progress bar in SwiftUI

Related tutorials:

Questions, comments or suggestions? Follow us on Twitter @theswiftguide

 

Sours: https://www.simpleswiftguide.com/how-to-build-a-circular-progress-bar-in-swiftui/

Circle bar progress create swift

Create circular Progress Bar in iOS


It is very important to know how to create a circular progress bar for iOS developers, almost every application have this.

This is mainly used in showing the downloading status, loading status or any other progress related thing.

Creating Circular Progress bar may become very tedious for new programmers and they might struggle working with it.

There are multiple way one can create circular progress bar. In this post we will be seeing one of the simplest and easiest way to create circular progress bar.

So let’s get started

Step 1 − Open Xcode, Single View Application, name it CircularProgress.

So we will be creating an application with 3 buttons having percentage and one circular progress view, where on tapping the buttons the progress view will change based on percentage.

Step 2 − Create new class, File -→ add new file -→ Cocoa Touch class -→ CircularProgressView of UIView class.

Step 3 − Create UI, Add UI view and add the class CircularProgressView of the same as shown below in the image, add three buttons and name them 30%, 60% and 95%.

Create @IBAction for all the three buttons in ViewController.swift and name them as shown below

@IBAction func btn95(_ sender: Any) { } @IBAction func btn30(_ sender: Any) { } @IBAction func btn60(_ sender: Any) { }

Create @IBoutlet for UI View in ViewController.swift and name it as below

@IBOutlet weak var circularProgress: CircularProgressView!

Step 4 − In CircularProgressView.swift, create two object progress layer and track layer of type CAShapeLayer().

var progressLyr = CAShapeLayer() var trackLyr = CAShapeLayer()

Step 5 Write did set methods to set progressLyr and trackLyr as below

var progressClr = UIColor.white {    didSet {       progressLyr.strokeColor = progressClr.cgColor    } } var trackClr = UIColor.white {    didSet {       trackLyr.strokeColor = trackClr.cgColor    } }

Here we are setting the property progressLyr and trackLyr.

didSet is a property observer, Property observers observe and respond to changes in a property’s value. Property observers are called every time a property’s value is set, even if the new value is the same as the property’s current value

Step 5 − Add makeCircularPath function and add below code.

func makeCircularPath() {    self.backgroundColor = UIColor.clear    self.layer.cornerRadius = self.frame.size.width/2    let circlePath = UIBezierPath(arcCenter: CGPoint(x: frame.size.width/2, y: frame.size.height/2), radius: (frame.size.width - 1.5)/2, startAngle: CGFloat(-0.5 * .pi), endAngle: CGFloat(1.5 * .pi), clockwise: true)    trackLyr.path = circlePath.cgPath    trackLyr.fillColor = UIColor.clear.cgColor    trackLyr.strokeColor = trackClr.cgColor    trackLyr.lineWidth = 5.0    trackLyr.strokeEnd = 1.0    layer.addSublayer(trackLyr)    progressLyr.path = circlePath.cgPath    progressLyr.fillColor = UIColor.clear.cgColor    progressLyr.strokeColor = progressClr.cgColor    progressLyr.lineWidth = 10.0    progressLyr.strokeEnd = 0.0    layer.addSublayer(progressLyr) }

In this function we are creating a circular path, defining the parameters of it and it’s behaviour.

Step 6 − Add required init function, when we design the UI from storyboard we should be using required init, when you design the UI programmatically we will use override init, in our case we’re going to use require init.

required init?(coder aDecoder: NSCoder) {    super.init(coder: aDecoder)    makeCircularPath() }

Step7 − Now we want to animate the progress so create new function setProgressWithAnimation and write the below code

func setProgressWithAnimation(duration: TimeInterval, value: Float) {    let animation = CABasicAnimation(keyPath: "strokeEnd")    animation.duration = duration    animation.fromValue = 0    animation.toValue = value    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)    progressLyr.strokeEnd = CGFloat(value)    progressLyr.add(animation, forKey: "animateprogress") }

We’re done, your final code for CircularProgressView.swift should look like this

import UIKit class CircularProgressView: UIView {    var progressLyr = CAShapeLayer()    var trackLyr = CAShapeLayer()    required init?(coder aDecoder: NSCoder) {       super.init(coder: aDecoder)       makeCircularPath()    }    var progressClr = UIColor.white {       didSet {          progressLyr.strokeColor = progressClr.cgColor       }    }    var trackClr = UIColor.white {       didSet {          trackLyr.strokeColor = trackClr.cgColor       }    }    func makeCircularPath() {       self.backgroundColor = UIColor.clear       self.layer.cornerRadius = self.frame.size.width/2       let circlePath = UIBezierPath(arcCenter: CGPoint(x: frame.size.width/2, y: frame.size.height/2), radius: (frame.size.width - 1.5)/2, startAngle: CGFloat(-0.5 * .pi), endAngle: CGFloat(1.5 * .pi), clockwise: true)       trackLyr.path = circlePath.cgPath       trackLyr.fillColor = UIColor.clear.cgColor       trackLyr.strokeColor = trackClr.cgColor       trackLyr.lineWidth = 5.0       trackLyr.strokeEnd = 1.0       layer.addSublayer(trackLyr)       progressLyr.path = circlePath.cgPath       progressLyr.fillColor = UIColor.clear.cgColor       progressLyr.strokeColor = progressClr.cgColor       progressLyr.lineWidth = 10.0       progressLyr.strokeEnd = 0.0       layer.addSublayer(progressLyr)    }    func setProgressWithAnimation(duration: TimeInterval, value: Float) {       let animation = CABasicAnimation(keyPath: "strokeEnd")       animation.duration = duration       animation.fromValue = 0       animation.toValue = value       animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)       progressLyr.strokeEnd = CGFloat(value)       progressLyr.add(animation, forKey: "animateprogress")    } }

Step 8 − Run the above code just to check everything works fine, you should see your UI as below but non-functional as we have not added any code in ViewController.swift

Step 9 − Let’s add some code in ViewController.swift.

Write the below line in viewDidLoad(), this will specify the color of the progress bar

circularProgress.trackClr = UIColor.cyan circularProgress.progressClr = UIColor.purple

Add below lines in your button functionality, with duration of 95%, 30% and 60%

@IBAction func btn95(_ sender: Any) {    circularProgress.setProgressWithAnimation(duration: 1.0, value: 0.95) } @IBAction func btn30(_ sender: Any) {    circularProgress.setProgressWithAnimation(duration: 1.0, value: 0.30) } @IBAction func btn60(_ sender: Any) {    circularProgress.setProgressWithAnimation(duration: 1.0, value: 0.60) }

Finally your ViewController.swift should have below code

import UIKit class ViewController: UIViewController {    @IBOutlet weak var circularProgress: CircularProgressView!    override func viewDidLoad() {       super.viewDidLoad()       circularProgress.trackClr = UIColor.cyan       circularProgress.progressClr = UIColor.purple    }    @IBAction func btn95(_ sender: Any) {       circularProgress.setProgressWithAnimation(duration: 1.0, value: 0.95)    }    @IBAction func btn30(_ sender: Any) {       circularProgress.setProgressWithAnimation(duration: 1.0, value: 0.30)    }    @IBAction func btn60(_ sender: Any) {       circularProgress.setProgressWithAnimation(duration: 1.0, value: 0.60)    } }

In the button function we are calling setProgressWithAnimation with values and duration.

That’s it we’re done, run the application and tap on 30% or 60% or 95%. You’ll see the view animating.

Sours: https://www.tutorialspoint.com/create-circular-progress-bar-in-ios
Create Progress Bar in App (Swift 5, Xcode 12) - iOS Development 2020

.

You will also like:

.



142 143 144 145 146