Draw Circle in Uiview Swift

Update note: Andrew Kharchyshyn updated this tutorial for iOS xiii, Swift 5 and Xcode 11. Caroline Begbie wrote the original.

You simply finished an app. It works fine, but the interface lacks mode and grace. You could give it a makeover by drawing several sizes of custom control images in Photoshop and hope Apple doesn't release a @4x retina screen. That plan, however, lacks strategy and sounds time-consuming. Alternatively, you could utilize Core Graphics to create an image that scales crisply for any device size.

Core Graphics is Apple's vector cartoon framework. It'southward a large, powerful application programming interface (API) with many tools to chief and cool features like @IBDesignable and @IBInspectable.

Just never fear! This three-part series takes a modern approach to Cadre Graphics. It starts dull and eases you in with fun, engaging exercises. Past the finish, you'll exist able to create stunning graphics for your apps.

So sit back and relax with your favorite beverage. It's time to learn Core Graphics!

Getting Into the Flo

Imagine a doctor recommends you potable eight spectacles of water a day. No problem, you recollect. Simply subsequently a few days, you realize how easy it is to lose track. Did yous down iii glasses this afternoon or two? Did you have your water canteen at your desk yesterday or the twenty-four hour period earlier?

In this tutorial, y'all'll create an app to track your drinking habits. With it, every time yous smoothen off a refreshing glass of H2O, y'all tap a counter push. As data accumulate, the app volition create a graph displaying your weekly consumption.

This app will exist named Flo, and here it is in its completed celebrity:

completed Flo app

Note: This tutorial is the first in a 3-function series. In part one, you'll create three controls using UIKit's drawing methods. In part 2, you'll swoop deeper into Core Graphics contexts and describe the graph. In part three, you'll create the patterned background, terminate Flo and award yourself a homemade Core Graphics medal. :]

Getting Started

Download the project materials by clicking the Download Materials button at the acme or bottom of this tutorial. Open the starter project in Xcode.

Build and run. You'll see the post-obit:

empty screen

You now have a starter project with a storyboard and a view controller, the residuum is for yous to build!

Creating a Custom Drawing on Views

There are iii steps for custom drawings:

  1. Create a UIView subclass.
  2. Override draw(_:) and add some Core Graphics drawing code.
  3. Have pride in your work. :]

You'll attempt this out by designing a custom plus button. It will await like this:

custom-drawn plus button

Create a new file by selecting FileNewFile…. Then choose iOSSourceCocoa Touch Class. Click Next.

On this screen, proper name the new class PushButton, make information technology a bracket of UIButton, and ensure the language is Swift. Click Next and then Create.

Note: Considering UIButton is a subclass of UIView, all of the methods in UIView, such as draw(_:), will be available in UIButton.

In Master.storyboard, drag a UIButton into the view controller's view, and select the button in Document Outline.

In the Identity inspector, alter the class to use your own PushButton.

Identity Inspector Push Button

Setting Auto Layout Constraints

Next yous'll fix the Auto Layout constraints:

  1. With the button selected, Control-drag from the center of the push button slightly left while staying within the button. Cull Width from the pop-up menu.
  2. With the button selected, Command-drag from the centre of the push slightly up while staying inside the push. Choose Peak from the pop-up menu.
  3. Control-elevate left from inside the button to outside the button. Choose Center Vertically in Container.
  4. Control-drag upward from inside the button to outside the push. Choose Centre Horizontally in Container.

This creates the iv required Auto Layout constraints. Y'all can now run across them in the Size inspector:

Auto Layout Constraints

Click Edit on Align eye Y to, and ready its constant to 100. This change shifts the vertical position of the push from the centre to 100 points below the middle. Similarly, alter Width and Height constants to 100. The final constraints should look like this:

The constraints inspector showing width and height constraints with a constant of 100, a center Y constraint with a constant of 100, and a center X constraint.

In the Attributes inspector, remove the default title Push.

remove default title from attributes inspector

Y'all could build and run the app right now, but if you did, y'all'd meet a blank screen. Time to fix that!

Cartoon the Push

Recall the button you're trying to make is circular:

Add Button Final

To draw a shape in Core Graphics, y'all define a path that tells Core Graphics the line to trace — such every bit two straight lines for the plus — or the line to fill — such as the circle. If you're familiar with Illustrator or the vector shapes in Photoshop, then you'll empathise paths.

There are three fundamentals to know near paths:

  • A path can be stroked and filled.
  • A stroke outlines the path in the current stroke colour.
  • A make full will fill a closed path with the current fill colour.

An like shooting fish in a barrel way to create a Core Graphics path is a handy grade chosen UIBezierPath. This form lets you develop paths with a user-friendly API. The paths tin be based on lines, curves, rectangles or a series of connected points.

Start past using UIBezierPath to create a path and so filling it with a green colour. Open PushButton.swift and add this method:

override func describe(_ rect: CGRect) {   permit path = UIBezierPath(ovalIn: rect)   UIColor.green.setFill()   path.fill() }        

Y'all created an oval-shaped UIBezierPath the size of the rectangle passed to it. In this case, it'll be the size of the 100×100 push button you defined in the storyboard, so the oval will be a circle.

Since paths don't draw anything, y'all tin define them without an available drawing context. To depict the path, you set a fill up color on the electric current context and then fill the path. You'll larn more well-nigh this later.

Build and run. You'll run across the light-green circle.

screen with green circle

So far, you've discovered how to brand custom-shaped views. You did this by creating a UIButton, overriding draw(_:) and adding UIButton to your storyboard.

Peeking Behind the Core Graphics Curtain

Each UIView has a graphics context. All cartoon for the view renders into this context before being transferred to the device'south hardware.

iOS updates the context by calling draw(_:) whenever the view needs to be updated. This happens when:

  • The view is new to the screen.
  • Other views on peak of it move.
  • The view's hidden property changes.
  • Y'all explicitly call setNeedsDisplay() or setNeedsDisplayInRect() on the view.

Annotation: Whatever drawing done in draw(_:) goes into the view's graphics context. Be enlightened that if you draw exterior of draw(_:), y'all'll take to create your own graphics context.

You lot haven't used Core Graphics withal in this tutorial, because UIKit has wrappers around many of the Core Graphics functions. A UIBezierPath, for example, is a wrapper for a CGMutablePath, which is the lower-level Core Graphics API.

Annotation: Never call draw(_:) directly. If your view is not being updated, and so phone call setNeedsDisplay().

setNeedsDisplay() does non itself call draw(_:), but it flags the view as "dirty," triggering a redraw using depict(_:) on the next screen update cycle. Even if you telephone call setNeedsDisplay() five times in the aforementioned method, you'll call draw(_:) only one time.

Introducing @IBDesignable

Creating code to depict a path and then running the app to see what it looks like is equally exciting every bit an introductory form on 1920'due south tax lawmaking. Thankfully, y'all've got options.

Live Rendering allows views to draw themselves more than accurately in a storyboard by running draw(_:). What's more, the storyboard will immediately update to changes in draw(_:). All you lot need is a single attribute!

Add the following only before the class declaration while in PushButton.swift:

@IBDesignable        

This enables Live Rendering. Return to Principal.storyboard. You'll see that your button is a green circle, just like when you build and run.

Next, yous'll set upward your screen to have the storyboard and lawmaking side-by-side.

Practise this by selecting PushButton.swift to show the lawmaking. Then, Option-click Principal.storyboard in Project navigator. You will run into the ii files side-by-side:

two files showing PushButton.swift and Main.storyboard

Shut the document outline at the left of the storyboard. Do this either by dragging the edge of the document outline pane or clicking the push button at the bottom of the storyboard:

close document outline

When you're done, your screen will look like this:

two files showing PushButton.swift and Main.storyboard

In draw(_:), locate the following code:

UIColor.green.setFill()        

Then change that code to:

UIColor.blueish.setFill()        

In the storyboard, you'll see make full color change from green to blue. Pretty cool!

button now has blue fill

Time to create the lines for that plus sign.

Drawing Into the Context

Cadre Graphics uses what's called a "painter's model". When you lot describe into a context, it's almost similar making a painting. You lay down a path and fill it, and and then lay downward another path on top and make full it. You can't change the pixels that have been laid down, only you tin can paint over them.

This prototype from Apple's documentation shows how this works. Simply like painting on a sheet, the guild in which you draw is critical.

add plus sign

Your plus sign will go along acme of the blueish circumvolve, then you must lawmaking the bluish circle get-go and and so the plus sign. Sure, you could draw two rectangles for the plus sign, merely it's easier to describe a path and then stroke it with the desired thickness.

Add this struct and these constants within of PushButton:

private struct Constants {   static let plusLineWidth: CGFloat = three.0   static let plusButtonScale: CGFloat = 0.6   static let halfPointShift: CGFloat = 0.five }    private var halfWidth: CGFloat {   return bounds.width / 2 }    private var halfHeight: CGFloat {   render premises.height / 2 }        

Next, add this lawmaking at the cease of draw(_:) to draw the horizontal nuance of the plus sign:

//set up upwardly the width and height variables //for the horizontal stroke allow plusWidth = min(premises.width, bounds.height)    * Constants.plusButtonScale let halfPlusWidth = plusWidth / ii  //create the path let plusPath = UIBezierPath()  //set the path'due south line width to the superlative of the stroke plusPath.lineWidth = Constants.plusLineWidth  //move the initial betoken of the path //to the start of the horizontal stroke plusPath.move(to: CGPoint(   ten: halfWidth - halfPlusWidth,   y: halfHeight))  //add a point to the path at the end of the stroke plusPath.addLine(to: CGPoint(   x: halfWidth + halfPlusWidth,   y: halfHeight))  //set the stroke color UIColor.white.setStroke()  //draw the stroke plusPath.stroke()        

In this block, you set upwards a UIBezierPath. You gave it a first position on the left side of the circle. You drew to the end position at the right side of the circumvolve. Then you stroked the path outlined in white.

In your storyboard, you now take a blue circle sporting a dash in the eye:

Blue circle with dash

Note: Call up that a path simply consists of points. An easy mode to grasp the concept is to imagine you have a pen in paw. You identify two dots on a page. You then identify the pen at the starting point and draw a line to the next point.

That's essentially what y'all did with the to a higher place code by using move(to:) and addLine(to:).

Run the application on either an iPad two or an iPhone eight Plus simulator, and yous'll notice the dash is not as crisp equally it should be. Information technology has a stake blue line encircling information technology.

Dash is pixeled

What's upward with that?

Analyzing Points and Pixels

Dorsum in the days of the starting time iPhones, points and pixels occupied the aforementioned space and were the same size. This made them basically the same thing. When retina iPhones came around, they sported four times the pixels on screen for the same number of points.

Similarly, the iPhone 8 Plus has again increased the number of pixels for the same points.

Note: The following is conceptual; actual hardware pixels may differ. For case, after rendering 3x, the iPhone 8 Plus downsamples to display the full image on the screen. To larn more virtually iPhone downsampling, check out this great post.

Beneath is a grid of 12×12 pixels with points shown in gray and white. The iPad 2 is a straight mapping of points to pixels, so 1x. The iPhone eight is a 2x retina screen with 4 pixels to a point. Finally, the iPhone 8 Plus is a 3x retina screen with 9 pixels to a betoken.

pixel comparisons

The line you only drew is 3 points high. Lines stroke from the middle of the path, so 1.five points will draw on either side of the centerline of the path.

This motion picture shows drawing a three-point line on each of the devices. You can run across that devices with 1x and 2x resolutions resulted in the line existence drawn beyond half a pixel — which, of class, can't be washed. And then, iOS anti-aliases the one-half-filled pixels with a colour halfway between the 2 colors. The resulting line looks fuzzy.

One Pixel Line Demonstrated

In reality, retina devices with 3x resolution have so many pixels you probably won't notice the fuzziness. But if you're developing for non-retina screens like the iPad 2, you should do what you can to avoid anti-aliasing.

If you take oddly sized straight lines, you demand to position them at plus or minus 0.v points to preclude anti-aliasing. If you look at the diagrams to a higher place, you'll see that a half-signal on 1x screen volition motion the line upward half a pixel. One-half a point will manage a whole pixel on 2x and one-and-a-half pixels on 3x.

In describe(_:), replace move(to:) and addLine(to:) with:

//move the initial point of the path //to the get-go of the horizontal stroke plusPath.motility(to: CGPoint(   10: halfWidth - halfPlusWidth + Constants.halfPointShift,   y: halfHeight + Constants.halfPointShift))      //add together a point to the path at the stop of the stroke plusPath.addLine(to: CGPoint(   x: halfWidth + halfPlusWidth + Constants.halfPointShift,   y: halfHeight + Constants.halfPointShift))        

Because you're now shifting the path past one-half a point, iOS volition at present render the lines sharply on all three resolutions.

Note: For pixel perfect lines, you can draw and fill a UIBezierPath(rect:) instead of a line. Then utilize the view'due south contentScaleFactor to calculate the width and peak of the rectangle. Different strokes that draw outwards from the center of the path, fills merely describe inside the path.

Add the vertical stroke of the plus after the previous ii lines of code, but earlier setting the stroke colour in draw(_:).

//Vertical Line   plusPath.motility(to: CGPoint(   x: halfWidth + Constants.halfPointShift,   y: halfHeight - halfPlusWidth + Constants.halfPointShift))        plusPath.addLine(to: CGPoint(   x: halfWidth + Constants.halfPointShift,   y: halfHeight + halfPlusWidth + Constants.halfPointShift))        

As you can see, it is almost the aforementioned lawmaking you used to describe the horizontal line on your push.

You should now see the live rendering of the plus button in your storyboard. This completes the drawing for the plus button.

plus button

Introducing @IBInspectable

At that place may come a moment when yous tap a push button more than necessary to ensure it registers. Every bit the app developer, yous'll demand to provide a way to contrary such overzealous tapping. You demand a minus button.

Your minus button will be identical to your plus push button, except information technology will forgo the vertical bar and sport a different color. You'll employ the same PushButton for the minus push button. You'll declare what sort of button information technology is and its color when you add information technology to your storyboard.

@IBInspectable is an aspect you lot can add together to a property that makes it readable by Interface Builder. This ways that you will be able to configure the color for the button in your storyboard instead of in code.

At the pinnacle of PushButton, add these 2 properties:

@IBInspectable var fillColor: UIColor = .green @IBInspectable var isAddButton: Bool = true        

Notation: With @IBInspectable, you must explicitly specify the blazon of your properties. Otherwise, y'all may confront an event with Xcode struggling to resolve the blazon.

Locate the fill color code at the tiptop of draw(_:). It looks like this:

UIColor.blue.setFill()        

Change it to this:

fillColor.setFill()        

The push will plough green in your storyboard view.

Surround the vertical line lawmaking in describe(_:) with this if argument:

//Vertical Line  if isAddButton {   //vertical line lawmaking move(to:) and addLine(to:) } //existing lawmaking //gear up the stroke colour UIColor.white.setStroke() plusPath.stroke()        

This makes it so you lot merely describe the vertical line if isAddButton is set. This fashion, the button can exist either a plus or a minus button.

In your storyboard, select the push push button view. The two backdrop you lot declared with @IBInspectable appear at the top of the Attributes inspector:

plus button properties in attributes inspector

Turn Is Add Push button to Off. Then change the color by going to Fill ColourCustom…Color SlidersRGB Sliders. Enter the values in each input field next to the colors, RGB(87, 218, 213). Information technology looks similar this:

change fill color and is add button properties

The changes will take identify in your storyboard:

minus button

Pretty cool. At present change Is Add Button back to On to return the button to a plus button.

Adding a Second Button

Add a new Button to the storyboard and select it, placing it under your existing button.

Identity Inspector Push Button

Modify its class to PushButton equally you did it with previous one. Yous'll run across a green plus push button nether your erstwhile plus button.

remove default title

In the Attributes inspector, alter Fill Color to RGB(238, 77, 77), change Is Add Button to Off, and remove the default title Button.

Add the Automobile Layout constraints for the new view. It's similar to what y'all did before:

  • With the button selected, Control-drag from the center of the button slightly to the left while staying within the push. Then choose Width from the pop-upward carte.
  • With the button selected, Command-drag from the center of the button slightly upwards while staying inside the button. Choose Meridian from the pop-up menu.
  • Control-elevate left from within the button to outside the push button. Choose Middle Horizontally in Container.
  • Control-drag upward from the bottom push to the top button. Choose Vertical Spacing.

After you add the constraints, edit their abiding values in the Size inspector to match these:

change values in size inspector

Build and run.

screen with Plus and Minus buttons

You now have a reusable customizable view that yous can add to whatsoever app. Information technology'south besides well-baked and sharp on whatsoever size device.

Calculation Arcs with UIBezierPath

The next customized view you'll create is this one:

counter view

This looks like a filled shape, but the arc is a fat-stroked path. The outlines are another stroked path consisting of two arcs.

Create a new file past selecting FileNewFile…. And so choose Cocoa Impact Class, and proper noun the new course CounterView. Make it a bracket of UIView and ensure the language is Swift. Click Next, and then click Create.

Supersede the code with:

import UIKit  @IBDesignable class CounterView: UIView {   private struct Constants {     static let numberOfGlasses = eight     static allow lineWidth: CGFloat = five.0     static permit arcWidth: CGFloat = 76          static var halfOfLineWidth: CGFloat {       return lineWidth / 2     }   }      @IBInspectable var counter: Int = five   @IBInspectable var outlineColor: UIColor = UIColor.bluish   @IBInspectable var counterColor: UIColor = UIColor.orange      override func depict(_ rect: CGRect) {   } }        

Hither you created a struct with constants. You'll apply them when drawing. The odd ane out, numberOfGlasses, is the target number of glasses to drink per twenty-four hours. When this figure is reached, the counter volition be at its maximum.

Y'all also created three @IBInspectable properties that yous tin can update in the storyboard. counter keeps track of the number of glasses consumed. It's an @IBDesignable property because it is useful to have the ability to modify it in the storyboard, specially for testing the counter view.

Get to Main.storyboard and add a UIView above the plus PushButton. Add the Auto Layout constraints for the new view. Information technology'southward similar to what you did before:

  1. With the view selected, Control-drag from the eye of the push button slightly left while staying within the view. Choose Width from the pop-up menu.
  2. Similarly, with the view selected, Command-drag from the heart of the button slightly upwardly while staying within the view. Choose Peak from the pop-upwardly menu.
  3. Control-drag left from inside the view to outside the view. Choose Center Horizontally in Container.
  4. Command-elevate downwardly from the view to the top push button. Cull Vertical Spacing.

Edit the constraint constants in the Size inspector to look like this:

edit constants in size inspector

In the Identity inspector, modify the class of the UIView to CounterView. Any cartoon that you code in draw(_:) volition at present appear in the view. Just you lot haven't added any…yet!

Enjoying an Impromptu Math Lesson

We interrupt this tutorial for a brief, and hopefully un-terrifying message from mathematics. Equally the The Hitchhiker'south Guide to the Milky way advises us, Don't Panic. :]

Cartoon in the context is based on this unit circumvolve. A unit circle is a circle with a radius of 1.0.

high school level math

The cherry arrow shows where your arc will start and end, drawing in a clockwise management. You lot'll draw an arc from the position 3π/4 radians — that's the equivalent of 135º — clockwise to π/four radians — that's 45º.

Radians are by and large used in programming instead of degrees, and thinking in radians means you lot won't have to catechumen to degrees every time you piece of work with circles. Heads upwardly: You'll need to figure out the arc length later, and radians will come up into play then.

An arc's length in a unit of measurement circle with a radius of i.0 is the aforementioned as the angle'southward measurement in radians. Looking at the diagram to a higher place, for instance, the length of the arc from 0º to 90º is π/2. To calculate the length of the arc in a real situation, take the unit circle arc length and multiply it past the actual radius.

To calculate the length of the reddish arrow above, you lot would summate the number of radians it spans: 2π – end of arrow (3π/iv) + point of arrow (π/4) = 3π/2.

In degrees that would exist: 360º – 135º + 45º = 270º.

And that'south the end of our impromptu math lesson!

a heart-emoji for math

Returning to Arcs

In CounterView.swift, add this code to draw(_:) to draw the arc:

// 1 let center = CGPoint(x: bounds.width / two, y: bounds.height / 2)  // 2 let radius = max(bounds.width, premises.meridian)  // 3 permit startAngle: CGFloat = three * .pi / 4 let endAngle: CGFloat = .pi / 4  // 4 permit path = UIBezierPath(   arcCenter: center,   radius: radius/2 - Constants.arcWidth/two,   startAngle: startAngle,   endAngle: endAngle,   clockwise: true)  // v path.lineWidth = Constants.arcWidth counterColor.setStroke() path.stroke()        

Here's what each department does:

  1. Define the eye betoken you lot'll rotate the arc around.
  2. Calculate the radius based on the maximum dimension of the view.
  3. Define the kickoff and finish angles for the arc.
  4. Create a path based on the middle point, radius and angles you divers.
  5. Set the line width and colour before finally stroking the path.

Imagine drawing this with a compass. Yous'd put the bespeak of the compass in the center, open the arm to the radius you demand, load it with a pen and spin information technology to depict your arc.

In this code, middle is the bespeak of the compass. radius is the width the compass is open, minus half the width of the pen. And the arc width is the width of the pen.

Annotation: This is more often than not all you need to know when drawing arcs. But if yous want to dive further into this topic, and so Cadre Graphics Tutorial on Arcs and Paths will help.

Build and run. This is what you'll see:

screen with an arc and plus and minus buttons

Outlining the Arc

When you indicate you've enjoyed a cool glass of h2o, an outline on the counter volition evidence you lot your progress toward the eight-glass goal. This outline will consist of two arcs, one outer and one inner, and two lines connecting them.

In CounterView.swift , add this lawmaking to the end of draw(_:):

//Describe the outline  //i - first calculate the difference between the two angles //ensuring it is positive permit angleDifference: CGFloat = ii * .pi - startAngle + endAngle //then calculate the arc for each single glass let arcLengthPerGlass = angleDifference / CGFloat(Constants.numberOfGlasses) //then multiply out past the actual glasses boozer let outlineEndAngle = arcLengthPerGlass * CGFloat(counter) + startAngle  //ii - draw the outer arc let outerArcRadius = bounds.width/2 - Constants.halfOfLineWidth let outlinePath = UIBezierPath(   arcCenter: center,   radius: outerArcRadius,   startAngle: startAngle,   endAngle: outlineEndAngle,   clockwise: true)  //three - draw the inner arc let innerArcRadius = bounds.width/2 - Constants.arcWidth   + Constants.halfOfLineWidth  outlinePath.addArc(   withCenter: eye,   radius: innerArcRadius,   startAngle: outlineEndAngle,   endAngle: startAngle,   clockwise: false)      //four - close the path outlinePath.close()      outlineColor.setStroke() outlinePath.lineWidth = Constants.lineWidth outlinePath.stroke()        

A few things to go through hither:

  1. outlineEndAngle is the angle where the arc should end; it'southward calculated using the current counter value.
  2. outlinePath is the outer arc. UIBezierPath() takes the radius to calculate the length of the arc equally this arc is not a unit of measurement circle.
  3. Adds an inner arc to the first arc. It has the same angles but draws in reverse. That's why clockwise was set up to false. Too, this draws a line betwixt the inner and outer arc automatically.
  4. Closing the path automatically draws a line at the other end of the arc.

With counter in CounterView.swift ready to 5, your CounterView volition wait similar this in the storyboard:

view counter view

Open Main.storyboard and select CounterView. In the Attributes inspector, change Counter to check out your cartoon lawmaking. You'll find it is completely interactive. Experiment by adjusting the counter to be more than than 8 and less than cypher.

Change Counter Color to RGB(87, 218, 213), and alter Outline Color to RGB(34, 110, 100).

change counter color and outline color

Making information technology All Work

Congrats! You take the controls. Next, y'all'll wire them up and so the plus push button increments the counter and the minus button decrements the counter.

In Main.storyboard, elevate a UILabel to the center of Counter View. Make sure information technology is a subview of Counter View. Add constraints to center the label vertically and horizontally. When you lot end, it will have constraints that await like this:

add constraints to label

In the Attributes inspector, change Alignment to center, font size to 36 and the default label championship to viii.

change properties in attributes inspector

Go to ViewController.swift and add together these properties to the top of the class:

//Counter outlets @IBOutlet weak var counterView: CounterView! @IBOutlet weak var counterLabel: UILabel!        

While still in ViewController.swift, add together this method to the end of the class:

@IBAction func pushButtonPressed(_ button: PushButton) {   if button.isAddButton {     counterView.counter += 1   } else {     if counterView.counter > 0 {       counterView.counter -= 1     }   }   counterLabel.text = String(counterView.counter) }        

Here you increment or decrement the counter depending on the button's isAddButton. Though you lot could fix the counter to fewer than zero, information technology probably won't work with Flo. Nobody can drink negative water. :]

Yous as well updated the counter value in the label.

Next, add this code to the cease of viewDidLoad() to ensure that the initial value of the counterLabel will be updated:

counterLabel.text = Cord(counterView.counter)        

In Main.storyboard, connect CounterView outlet and UILabel outlet. Connect the method to Impact Up Inside event of the 2 PushButtonsouth.

view controller's IBOutlet and IBAction connected to storyboard

Build and run.

See if your buttons update the counter label. They should. But you may notice the counter view isn't updating. Think fashion back to the kickoff of this tutorial. Remember, you just chosen describe(_:) when other views on superlative of information technology moved, its hidden property inverse, the view was new to the screen or the app called the setNeedsDisplay() or setNeedsDisplayInRect() on the view.

However, the counter view needs to be updated whenever the counter property is updated; otherwise, information technology looks like the app is busted.

Get to CounterView.swift and change the declaration of counter to:

@IBInspectable var counter: Int = five {   didSet {     if counter <=  Constants.numberOfGlasses {       //the view needs to be refreshed       setNeedsDisplay()     }   } }        

This code refreshes the view simply when the counter is less than or equal to the user'southward targeted glasses.

Build and run. Everything should now be working properly.

screen with two buttons and an arc with number 3 in the middle

Where to Go From Here?

You lot can download the completed version of the project using the Download Materials button at the top or bottom of this tutorial.

Astonishing! You've covered basic drawing in this tutorial. You can now change the shape of views in your UIs. Merely wait — there's more!

In Part 2 of this series, you'll explore Core Graphics contexts in more depth and create a graph of your water consumption over time.

If y'all'd like to learn more near custom layouts, consider the following resources:

  • Cheque out this page with listing of resources provided by Apple.
  • Follow our video course on Cadre Graphics if you prefer the video format.

If yous accept any questions or comments, please bring together the forum discussion below.

mallardthental.blogspot.com

Source: https://www.raywenderlich.com/8003281-core-graphics-tutorial-getting-started

Belum ada Komentar untuk "Draw Circle in Uiview Swift"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel