Draw Circle in Swift 4

Update annotation: Andrew Kharchyshyn updated this tutorial for iOS 13, Swift v and Xcode eleven. Caroline Begbie wrote the original.

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

Cadre Graphics is Apple's vector drawing framework. It's a big, powerful application programming interface (API) with many tools to master and absurd features like @IBDesignable and @IBInspectable.

Merely never fearfulness! This three-part serial takes a modern arroyo to Core Graphics. It starts slow and eases yous in with fun, engaging exercises. Past the terminate, you'll be able to create stunning graphics for your apps.

So sit back and relax with your favorite drinkable. It'due south time to learn Core Graphics!

Getting Into the Flo

Imagine a doctor recommends you drink viii glasses of water a day. No problem, you remember. Simply after a few days, you realize how easy it is to lose rail. Did you lot downwardly three glasses this afternoon or two? Did you have your water bottle at your desk-bound yesterday or the day before?

In this tutorial, you'll create an app to track your drinking habits. With information technology, every time you smooth off a refreshing glass of H2O, yous tap a counter button. Every bit data accumulate, the app will create a graph displaying your weekly consumption.

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

completed Flo app

Note: This tutorial is the outset in a 3-part series. In part 1, y'all'll create three controls using UIKit's cartoon methods. In part two, you'll dive deeper into Cadre Graphics contexts and draw the graph. In role three, you'll create the patterned background, finish Flo and award yourself a bootleg Core Graphics medal. :]

Getting Started

Download the projection materials by clicking the Download Materials push at the summit or bottom of this tutorial. Open the starter projection in Xcode.

Build and run. Y'all'll see the following:

empty screen

You at present have a starter project with a storyboard and a view controller, the rest is for you to build!

Creating a Custom Cartoon on Views

At that place are three steps for custom drawings:

  1. Create a UIView subclass.
  2. Override draw(_:) and add some Core Graphics drawing code.
  3. Accept pride in your piece of 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, name the new class PushButton, make it a subclass of UIButton, and ensure the language is Swift. Click Next and then Create.

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

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

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

Identity Inspector Push Button

Setting Automobile Layout Constraints

Next you'll set upward the Auto Layout constraints:

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

This creates the 4 required Auto Layout constraints. You lot can now see them in the Size inspector:

Auto Layout Constraints

Click Edit on Align center Y to, and prepare its abiding to 100. This modify shifts the vertical position of the button from the center to 100 points below the center. Similarly, change Width and Acme 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 Button.

remove default title from attributes inspector

You could build and run the app right now, but if yous did, you'd see a blank screen. Time to gear up that!

Drawing the Button

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

Add Button Final

To draw a shape in Core Graphics, you ascertain a path that tells Core Graphics the line to trace — such as ii straight lines for the plus — or the line to fill — such as the circumvolve. If yous're familiar with Illustrator or the vector shapes in Photoshop, then yous'll empathise paths.

In that location are three fundamentals to know near paths:

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

An easy manner to create a Core Graphics path is a handy class called UIBezierPath. This course lets you develop paths with a user-friendly API. The paths can be based on lines, curves, rectangles or a series of connected points.

Start by using UIBezierPath to create a path and so filling it with a green color. Open up PushButton.swift and add together this method:

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

You lot created an oval-shaped UIBezierPath the size of the rectangle passed to it. In this case, information technology'll be the size of the 100×100 button you defined in the storyboard, so the oval volition be a circle.

Since paths don't draw anything, yous can define them without an available cartoon context. To describe the path, you set a make full color on the current context and then fill up the path. You lot'll learn more about this subsequently.

Build and run. Yous'll see the green circle.

screen with green circle

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

Peeking Behind the Core Graphics Pall

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

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

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

Note: Whatsoever drawing done in draw(_:) goes into the view'south graphics context. Exist enlightened that if you draw exterior of draw(_:), you'll have to create your own graphics context.

You haven't used Cadre Graphics yet in this tutorial, considering 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 Cadre Graphics API.

Notation: Never call depict(_:) direct. If your view is non being updated, and so call setNeedsDisplay().

setNeedsDisplay() does not itself telephone call draw(_:), but it flags the view as "muddy," triggering a redraw using draw(_:) on the next screen update bicycle. Even if you call setNeedsDisplay() five times in the same method, you'll call draw(_:) only once.

Introducing @IBDesignable

Creating code to draw a path and and so running the app to see what it looks like is as exciting as an introductory grade on 1920's tax code. Thankfully, you've got options.

Alive Rendering allows views to draw themselves more accurately in a storyboard by running draw(_:). What'south more, the storyboard will immediately update to changes in draw(_:). All yous need is a unmarried attribute!

Add together the following but before the grade declaration while in PushButton.swift:

@IBDesignable        

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

Next, you'll fix your screen to have the storyboard and lawmaking side-by-side.

Practice this by selecting PushButton.swift to show the code. Then, Option-click Principal.storyboard in Projection navigator. You lot will run across 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 past dragging the edge of the document outline pane or clicking the button at the bottom of the storyboard:

close document outline

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

two files showing PushButton.swift and Main.storyboard

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

UIColor.light-green.setFill()        

Then change that lawmaking to:

UIColor.bluish.setFill()        

In the storyboard, you'll run across fill color change from greenish to blue. Pretty absurd!

button now has blue fill

Fourth dimension to create the lines for that plus sign.

Drawing Into the Context

Cadre Graphics uses what's chosen a "painter's model". When you describe into a context, it'south most like making a painting. You lay down a path and make full it, and and then lay down some other path on top and fill it. You can't change the pixels that have been laid downwards, but you tin pigment over them.

This image from Apple'due south documentation shows how this works. Merely similar painting on a sheet, the lodge in which you lot depict is critical.

add plus sign

Your plus sign will continue top of the blue circle, so yous must code the blue circle first and so the plus sign. Certain, y'all could depict two rectangles for the plus sign, but it's easier to draw a path and and then stroke it with the desired thickness.

Add this struct and these constants inside of PushButton:

private struct Constants {   static allow plusLineWidth: CGFloat = 3.0   static let plusButtonScale: CGFloat = 0.six   static let halfPointShift: CGFloat = 0.5 }    private var halfWidth: CGFloat {   return bounds.width / 2 }    private var halfHeight: CGFloat {   render bounds.height / ii }        

Side by side, add this code at the end of draw(_:) to depict the horizontal dash of the plus sign:

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

In this block, you gear up a UIBezierPath. Y'all gave it a start position on the left side of the circle. Y'all drew to the finish position at the right side of the circle. And so you stroked the path outlined in white.

In your storyboard, yous at present have a blueish circumvolve sporting a dash in the middle:

Blue circle with dash

Notation: Remember that a path simply consists of points. An easy way to grasp the concept is to imagine you have a pen in manus. Yous place two dots on a folio. You lot then identify the pen at the starting indicate and depict a line to the next point.

That's substantially what you lot did with the to a higher place code by using motion(to:) and addLine(to:).

Run the awarding on either an iPad ii or an iPhone 8 Plus simulator, and you'll observe the dash is not as crisp as it should be. It has a stake bluish line encircling information technology.

Dash is pixeled

What's up with that?

Analyzing Points and Pixels

Dorsum in the days of the get-go iPhones, points and pixels occupied the same space and were the same size. This made them basically the same affair. When retina iPhones came effectually, 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 example, after rendering 3x, the iPhone 8 Plus downsamples to display the full image on the screen. To larn more most iPhone downsampling, check out this bully mail.

Below is a grid of 12×12 pixels with points shown in greyness and white. The iPad 2 is a direct mapping of points to pixels, so 1x. The iPhone viii is a 2x retina screen with four pixels to a point. Finally, the iPhone eight Plus is a 3x retina screen with nine pixels to a point.

pixel comparisons

The line yous but drew is three points high. Lines stroke from the center of the path, so 1.5 points volition describe on either side of the centerline of the path.

This picture shows cartoon a 3-signal line on each of the devices. You can encounter that devices with 1x and 2x resolutions resulted in the line being drawn across half a pixel — which, of grade, can't exist done. So, iOS anti-aliases the half-filled pixels with a color halfway betwixt the two colors. The resulting line looks fuzzy.

One Pixel Line Demonstrated

In reality, retina devices with 3x resolution take and then many pixels you lot probably won't notice the fuzziness. But if you're developing for non-retina screens like the iPad 2, you should practise what you tin to avoid anti-aliasing.

If you accept oddly sized directly lines, you need to position them at plus or minus 0.v points to forbid anti-aliasing. If you look at the diagrams above, you lot'll come across that a half-point on 1x screen will move the line up half a pixel. Half a point will manage a whole pixel on 2x and one-and-a-half pixels on 3x.

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

//move the initial point of the path //to the start of the horizontal stroke plusPath.motion(to: CGPoint(   10: halfWidth - halfPlusWidth + Constants.halfPointShift,   y: halfHeight + Constants.halfPointShift))      //add a indicate to the path at the terminate of the stroke plusPath.addLine(to: CGPoint(   10: halfWidth + halfPlusWidth + Constants.halfPointShift,   y: halfHeight + Constants.halfPointShift))        

Because yous're now shifting the path by half a point, iOS volition at present render the lines sharply on all 3 resolutions.

Notation: For pixel perfect lines, yous tin draw and fill a UIBezierPath(rect:) instead of a line. And then use the view's contentScaleFactor to calculate the width and meridian of the rectangle. Unlike strokes that draw outwards from the center of the path, fills only draw inside the path.

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

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

As you can meet, it is about the aforementioned code you used to draw the horizontal line on your button.

You should now run into the alive rendering of the plus push in your storyboard. This completes the cartoon for the plus push.

plus button

Introducing @IBInspectable

There may come up a moment when you tap a button more than than necessary to ensure it registers. As the app programmer, you'll demand to provide a mode to contrary such overzealous borer. You need a minus button.

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

@IBInspectable is an attribute you can add together to a holding that makes information technology readable by Interface Builder. This means that you volition exist able to configure the colour for the button in your storyboard instead of in code.

At the top of PushButton, add these 2 properties:

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

Notation: With @IBInspectable, you must explicitly specify the type of your backdrop. Otherwise, you may face an issue with Xcode struggling to resolve the type.

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

UIColor.blue.setFill()        

Alter information technology to this:

fillColor.setFill()        

The button volition turn greenish in your storyboard view.

Surroundings the vertical line lawmaking in draw(_:) with this if statement:

//Vertical Line  if isAddButton {   //vertical line code motility(to:) and addLine(to:) } //existing code //set the stroke color UIColor.white.setStroke() plusPath.stroke()        

This makes it and then you only draw the vertical line if isAddButton is prepare. This way, the button tin can be either a plus or a minus button.

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

plus button properties in attributes inspector

Plough Is Add Button to Off. And so change the colour by going to Fill up ColorCustom…Color SlidersRGB Sliders. Enter the values in each input field next to the colors, RGB(87, 218, 213). Information technology looks like this:

change fill color and is add button properties

The changes will take place in your storyboard:

minus button

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

Adding a 2nd Button

Add a new Button to the storyboard and select it, placing information technology nether your existing push.

Identity Inspector Push Button

Change its class to PushButton as you did it with previous one. You'll run into a green plus button under your old plus button.

remove default title

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

Add the Auto Layout constraints for the new view. It's like to what you did before:

  • With the button selected, Control-drag from the center of the button slightly to the left while staying within the button. And so cull Width from the popular-up menu.
  • With the push selected, Control-drag from the heart of the push button slightly upwardly while staying within the button. Choose Height from the pop-upward menu.
  • Control-drag left from inside the button to outside the button. Cull Center Horizontally in Container.
  • Control-drag upwardly from the bottom button to the top push button. Choose Vertical Spacing.

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

change values in size inspector

Build and run.

screen with Plus and Minus buttons

You at present have a reusable customizable view that y'all tin can add to any app. It'due south too well-baked and sharp on any size device.

Adding Arcs with UIBezierPath

The adjacent customized view you'll create is this ane:

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 by selecting FileNewFile…. Then choose Cocoa Touch Class, and proper noun the new class CounterView. Make it a subclass of UIView and ensure the language is Swift. Click Adjacent, and and then click Create.

Supercede the lawmaking with:

import UIKit  @IBDesignable class CounterView: UIView {   private struct Constants {     static let numberOfGlasses = 8     static let lineWidth: CGFloat = 5.0     static allow arcWidth: CGFloat = 76          static var halfOfLineWidth: CGFloat {       render lineWidth / 2     }   }      @IBInspectable var counter: Int = five   @IBInspectable var outlineColor: UIColor = UIColor.blue   @IBInspectable var counterColor: UIColor = UIColor.orangish      override func draw(_ rect: CGRect) {   } }        

Here yous created a struct with constants. You lot'll use them when drawing. The odd one out, numberOfGlasses, is the target number of spectacles to potable per day. When this figure is reached, the counter will exist at its maximum.

You also created three @IBInspectable backdrop that y'all can update in the storyboard. counter keeps track of the number of glasses consumed. Information technology's an @IBDesignable property because it is useful to have the ability to change it in the storyboard, specially for testing the counter view.

Go to Main.storyboard and add a UIView in a higher place the plus PushButton. Add together the Auto Layout constraints for the new view. It'southward similar to what you did before:

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

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

edit constants in size inspector

In the Identity inspector, change the class of the UIView to CounterView. Any drawing that you code in draw(_:) will now appear in the view. Merely you 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'due south Guide to the Galaxy advises us, Don't Panic. :]

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

high school level math

The cerise arrow shows where your arc will start and end, cartoon in a clockwise direction. You'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 generally used in programming instead of degrees, and thinking in radians means you won't have to catechumen to degrees every fourth dimension you piece of work with circles. Heads upwardly: Y'all'll need to figure out the arc length subsequently, and radians will come up into play then.

An arc's length in a unit circumvolve with a radius of 1.0 is the same as the angle's measurement in radians. Looking at the diagram above, for example, the length of the arc from 0º to 90º is π/2. To calculate the length of the arc in a real state of affairs, take the unit circumvolve arc length and multiply it by the bodily radius.

To calculate the length of the red arrow higher up, you would summate the number of radians it spans: 2π – stop of arrow (3π/4) + indicate of arrow (π/iv) = 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 lawmaking to draw(_:) to draw the arc:

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

Here'due south what each section does:

  1. Ascertain the eye bespeak you'll rotate the arc around.
  2. Calculate the radius based on the maximum dimension of the view.
  3. Define the showtime and end angles for the arc.
  4. Create a path based on the eye indicate, radius and angles yous defined.
  5. Ready the line width and color before finally stroking the path.

Imagine drawing this with a compass. Y'all'd put the betoken of the compass in the center, open the arm to the radius you need, load information technology with a pen and spin information technology to draw your arc.

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

Note: This is generally all you need to know when drawing arcs. But if you desire to dive further into this topic, then 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 y'all indicate you've enjoyed a cool glass of water, an outline on the counter will show you your progress toward the eight-drinking glass goal. This outline volition consist of two arcs, one outer and one inner, and ii lines connecting them.

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

//Draw the outline  //1 - kickoff summate the departure betwixt the two angles //ensuring information technology is positive let angleDifference: CGFloat = 2 * .pi - startAngle + endAngle //then summate the arc for each unmarried drinking glass let arcLengthPerGlass = angleDifference / CGFloat(Constants.numberOfGlasses) //then multiply out by the actual glasses drunkard let outlineEndAngle = arcLengthPerGlass * CGFloat(counter) + startAngle  //2 - draw the outer arc let outerArcRadius = bounds.width/2 - Constants.halfOfLineWidth let outlinePath = UIBezierPath(   arcCenter: centre,   radius: outerArcRadius,   startAngle: startAngle,   endAngle: outlineEndAngle,   clockwise: truthful)  //3 - depict the inner arc let innerArcRadius = bounds.width/2 - Constants.arcWidth   + Constants.halfOfLineWidth  outlinePath.addArc(   withCenter: middle,   radius: innerArcRadius,   startAngle: outlineEndAngle,   endAngle: startAngle,   clockwise: false)      //iv - close the path outlinePath.close()      outlineColor.setStroke() outlinePath.lineWidth = Constants.lineWidth outlinePath.stroke()        

A few things to go through here:

  1. outlineEndAngle is the angle where the arc should stop; it's calculated using the current counter value.
  2. outlinePath is the outer arc. UIBezierPath() takes the radius to calculate the length of the arc as this arc is not a unit circle.
  3. Adds an inner arc to the first arc. It has the aforementioned angles but draws in reverse. That's why clockwise was ready to faux. Also, this draws a line betwixt the inner and outer arc automatically.
  4. Endmost the path automatically draws a line at the other end of the arc.

With counter in CounterView.swift set to five, your CounterView will await like this in the storyboard:

view counter view

Open Main.storyboard and select CounterView. In the Attributes inspector, change Counter to bank check out your drawing code. Yous'll discover it is completely interactive. Experiment by adjusting the counter to exist more eight and less than zilch.

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

change counter color and outline color

Making information technology All Work

Congrats! You have the controls. Next, you lot'll wire them upward and so the plus push increments the counter and the minus button decrements the counter.

In Principal.storyboard, drag a UILabel to the center of Counter View. Make sure it is a subview of Counter View. Add constraints to eye the label vertically and horizontally. When you finish, it will take constraints that expect like this:

add constraints to label

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

change properties in attributes inspector

Become to ViewController.swift and add 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 this method to the cease of the grade:

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

Hither you increment or decrement the counter depending on the button's isAddButton. Though yous could set the counter to fewer than null, it probably won't work with Flo. Nobody can drink negative water. :]

You also updated the counter value in the label.

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

counterLabel.text = String(counterView.counter)        

In Main.storyboard, connect CounterView outlet and UILabel outlet. Connect the method to Affect Upwards Inside consequence of the two PushButtonsouth.

view controller's IBOutlet and IBAction connected to storyboard

Build and run.

See if your buttons update the counter characterization. They should. But you may detect the counter view isn't updating. Call back manner back to the commencement of this tutorial. Recollect, y'all simply called draw(_:) when other views on top of it moved, its hidden property changed, 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, it looks like the app is busted.

Become to CounterView.swift and alter the proclamation of counter to:

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

This code refreshes the view only when the counter is less than or equal to the user's targeted spectacles.

Build and run. Everything should now be working properly.

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

Where to Become From Here?

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

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

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

If you'd like to larn more than about custom layouts, consider the following resource:

  • Cheque out this folio with list of resources provided past Apple.
  • Follow our video grade on Core Graphics if you prefer the video format.

If you take any questions or comments, please join the forum discussion beneath.

johnstonthervicarl.blogspot.com

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

Belum ada Komentar untuk "Draw Circle in Swift 4"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel