How to Draw a Circle in Xcode Storyboard

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

Yous just finished an app. It works fine, but the interface lacks mode and grace. You could give information technology a makeover by drawing several sizes of custom control images in Photoshop and hope Apple doesn't release a @4x retina screen. That program, still, lacks strategy and sounds fourth dimension-consuming. Alternatively, you lot could use Cadre Graphics to create an image that scales crisply for any device size.

Core Graphics is Apple'due south vector drawing framework. It'south a big, powerful application programming interface (API) with many tools to master and cool features similar @IBDesignable and @IBInspectable.

Simply never fearfulness! This 3-part serial takes a modern approach to Cadre Graphics. It starts slow and eases you in with fun, engaging exercises. Past the end, you'll be able to create stunning graphics for your apps.

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

Getting Into the Flo

Imagine a dr. recommends y'all potable eight glasses of h2o a day. No problem, y'all think. Merely afterward a few days, you realize how piece of cake information technology is to lose rail. Did y'all down three glasses this afternoon or two? Did you have your water canteen at your desk yesterday or the day before?

In this tutorial, you'll create an app to track your drinking habits. With it, every time you polish off a refreshing glass of H2O, you tap a counter button. Equally data accumulate, the app volition create a graph displaying your weekly consumption.

This app will be named Flo, and hither it is in its completed glory:

completed Flo app

Notation: This tutorial is the start in a 3-function series. In office one, you'll create 3 controls using UIKit'southward drawing methods. In role 2, you'll dive deeper into Core Graphics contexts and draw the graph. In office three, you'll create the patterned background, finish Flo and award yourself a homemade Core Graphics medal. :]

Getting Started

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

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

empty screen

You at present have a starter project with a storyboard and a view controller, the rest is for you lot 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 Cadre Graphics cartoon code.
  3. Take pride in your piece of work. :]

You'll try this out by designing a custom plus button. It volition expect like this:

custom-drawn plus button

Create a new file by selecting FileNewFile…. So choose iOSSourceCocoa Impact Class. Click Next.

On this screen, name the new class PushButton, brand it a subclass of UIButton, and ensure the linguistic communication is Swift. Click Side by side then Create.

Annotation: Because UIButton is a subclass of UIView, all of the methods in UIView, such as depict(_:), will exist bachelor in UIButton.

In Main.storyboard, elevate a UIButton into the view controller'south view, and select the push in Document Outline.

In the Identity inspector, change the form to utilize your own PushButton.

Identity Inspector Push Button

Setting Auto Layout Constraints

Next you'll set upwards the Automobile Layout constraints:

  1. With the button selected, Command-drag from the center of the button slightly left while staying within the button. Choose Width from the popular-upwards bill of fare.
  2. With the button selected, Control-drag from the heart of the button slightly up while staying within the button. Choose Height from the popular-upward menu.
  3. Control-drag left from inside the button to outside the push button. Choose Middle Vertically in Container.
  4. Control-drag up from inside the button to outside the button. Choose Center Horizontally in Container.

This creates the four required Auto Layout constraints. You can now meet them in the Size inspector:

Auto Layout Constraints

Click Edit on Align center Y to, and set its constant to 100. This change shifts the vertical position of the push button from the middle to 100 points below the eye. Similarly, change Width and Height constants to 100. The terminal 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

You could build and run the app right now, just if you lot did, you'd run into a blank screen. Fourth dimension to fix that!

Drawing the Push

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

Add Button Final

To describe a shape in Cadre Graphics, you define a path that tells Core Graphics the line to trace — such as two straight lines for the plus — or the line to fill up — such equally the circumvolve. If yous're familiar with Illustrator or the vector shapes in Photoshop, and so you'll sympathize paths.

In that location are iii fundamentals to know nigh paths:

  • A path can be stroked and filled.
  • A stroke outlines the path in the current stroke color.
  • A fill volition fill a airtight path with the current fill up color.

An easy style to create a Core Graphics path is a handy form chosen UIBezierPath. This grade lets you lot develop paths with a user-friendly API. The paths can be based on lines, curves, rectangles or a series of continued points.

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

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

You created an oval-shaped UIBezierPath the size of the rectangle passed to it. In this instance, it'll exist the size of the 100×100 button you lot defined in the storyboard, and then the oval will be a circle.

Since paths don't depict annihilation, you can ascertain them without an available drawing context. To describe the path, you lot set a fill color on the current context and so fill up the path. You lot'll learn more almost this later on.

Build and run. You'll meet the green circle.

screen with green circle

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

Peeking Backside 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'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 summit of it motility.
  • The view's hidden belongings changes.
  • You explicitly call setNeedsDisplay() or setNeedsDisplayInRect() on the view.

Note: Any drawing done in draw(_:) goes into the view's graphics context. Be aware that if yous depict outside of draw(_:), you'll take to create your own graphics context.

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

Note: Never phone call draw(_:) directly. If your view is not existence updated, then call setNeedsDisplay().

setNeedsDisplay() does not itself phone call draw(_:), only information technology flags the view every bit "dirty," triggering a redraw using describe(_:) on the next screen update cycle. Even if you call setNeedsDisplay() five times in the same method, you'll call depict(_:) only once.

Introducing @IBDesignable

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

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

Add the following just before the class proclamation while in PushButton.swift:

@IBDesignable        

This enables Alive Rendering. Return to Chief.storyboard. You'll meet that your button is a dark-green circumvolve, just like when you build and run.

Adjacent, you'll prepare up your screen to accept the storyboard and code side-past-side.

Do this by selecting PushButton.swift to show the code. Then, Option-click Main.storyboard in Project navigator. You volition see the two files side-past-side:

two files showing PushButton.swift and Main.storyboard

Shut the certificate outline at the left of the storyboard. Practise this either past dragging the edge of the certificate outline pane or clicking the button at the bottom of the storyboard:

close document outline

When you're washed, your screen will wait like this:

two files showing PushButton.swift and Main.storyboard

In draw(_:), locate the post-obit lawmaking:

UIColor.green.setFill()        

And so change that code to:

UIColor.blue.setFill()        

In the storyboard, you'll encounter make full color modify from green to bluish. Pretty cool!

button now has blue fill

Fourth dimension to create the lines for that plus sign.

Drawing Into the Context

Core Graphics uses what's called a "painter's model". When y'all draw into a context, it'due south almost similar making a painting. You lay down a path and fill information technology, and and so lay downwards some other path on top and make full it. Yous can't change the pixels that have been laid down, but y'all tin can paint over them.

This image from Apple tree's documentation shows how this works. Just like painting on a canvas, the order in which you draw is critical.

add plus sign

Your plus sign will go on top of the blue circle, and then y'all must code the blue circle outset so the plus sign. Sure, y'all could draw 2 rectangles for the plus sign, merely it'south easier to draw a path and and so stroke it with the desired thickness.

Add this struct and these constants inside of PushButton:

private struct Constants {   static permit plusLineWidth: CGFloat = 3.0   static let plusButtonScale: CGFloat = 0.6   static let halfPointShift: CGFloat = 0.5 }    private var halfWidth: CGFloat {   return premises.width / 2 }    private var halfHeight: CGFloat {   return bounds.height / ii }        

Next, add this code at the finish of depict(_:) to describe the horizontal nuance of the plus sign:

//ready the width and height variables //for the horizontal stroke let plusWidth = min(bounds.width, premises.tiptop)    * Constants.plusButtonScale let halfPlusWidth = plusWidth / ii  //create the path let plusPath = UIBezierPath()  //set up the path'south line width to the height of the stroke plusPath.lineWidth = Constants.plusLineWidth  //movement the initial indicate of the path //to the beginning of the horizontal stroke plusPath.move(to: CGPoint(   x: halfWidth - halfPlusWidth,   y: halfHeight))  //add a point to the path at the end of the stroke plusPath.addLine(to: CGPoint(   ten: halfWidth + halfPlusWidth,   y: halfHeight))  //fix the stroke colour UIColor.white.setStroke()  //depict the stroke plusPath.stroke()        

In this block, y'all fix up a UIBezierPath. You gave it a starting time position on the left side of the circle. You drew to the finish position at the right side of the circle. So you stroked the path outlined in white.

In your storyboard, you now have a blue circle sporting a dash in the center:

Blue circle with dash

Note: Call up that a path simply consists of points. An like shooting fish in a barrel style to grasp the concept is to imagine you have a pen in hand. Yous place 2 dots on a page. You then place the pen at the starting point and draw a line to the next point.

That'southward essentially what you did with the above code by using movement(to:) and addLine(to:).

Run the application on either an iPad 2 or an iPhone 8 Plus simulator, and you'll find the dash is not as crisp every bit it should be. It has a pale blue line encircling it.

Dash is pixeled

What's upward with that?

Analyzing Points and Pixels

Dorsum in the days of the get-go iPhones, points and pixels occupied the same infinite and were the same size. This made them basically the same thing. When retina iPhones came around, they sported iv times the pixels on screen for the same number of points.

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

Note: The following is conceptual; actual hardware pixels may differ. For example, subsequently rendering 3x, the iPhone 8 Plus downsamples to brandish the full image on the screen. To learn more near iPhone downsampling, check out this groovy mail.

Below is a grid of 12×12 pixels with points shown in gray and white. The iPad two is a direct mapping of points to pixels, so 1x. The iPhone 8 is a 2x retina screen with 4 pixels to a signal. Finally, the iPhone 8 Plus is a 3x retina screen with ix pixels to a point.

pixel comparisons

The line y'all simply drew is 3 points high. Lines stroke from the eye of the path, so 1.5 points will draw on either side of the centerline of the path.

This picture shows drawing a 3-point line on each of the devices. You lot can see that devices with 1x and 2x resolutions resulted in the line being drawn beyond half a pixel — which, of course, tin't be washed. And then, iOS anti-aliases the half-filled pixels with a color halfway between the two 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. Merely if you lot're developing for non-retina screens like the iPad 2, y'all should do what yous can to avoid anti-aliasing.

If yous have oddly sized straight lines, you need to position them at plus or minus 0.v points to prevent anti-aliasing. If you wait at the diagrams above, you'll meet that a half-point on 1x screen will move the line upwards 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 bespeak of the path //to the start of the horizontal stroke plusPath.move(to: CGPoint(   ten: halfWidth - halfPlusWidth + Constants.halfPointShift,   y: halfHeight + Constants.halfPointShift))      //add a point to the path at the end of the stroke plusPath.addLine(to: CGPoint(   x: halfWidth + halfPlusWidth + Constants.halfPointShift,   y: halfHeight + Constants.halfPointShift))        

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

Note: For pixel perfect lines, you can describe and make full a UIBezierPath(rect:) instead of a line. Then use the view's contentScaleFactor to summate the width and height of the rectangle. Unlike strokes that depict 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 earlier setting the stroke color 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))        

Equally you lot tin can run into, it is almost the same code you lot used to depict the horizontal line on your button.

Y'all should now see the alive rendering of the plus button in your storyboard. This completes the drawing for the plus push button.

plus button

Introducing @IBInspectable

There may come up a moment when you tap a button more necessary to ensure information technology registers. Every bit the app developer, you lot'll need to provide a mode to reverse such overzealous borer. You need a minus button.

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

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

At the top of PushButton, add these ii properties:

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

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

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

UIColor.blue.setFill()        

Change information technology to this:

fillColor.setFill()        

The push will turn greenish in your storyboard view.

Surround the vertical line code in depict(_:) 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 so you only draw the vertical line if isAddButton is set. This way, the button can exist either a plus or a minus button.

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

plus button properties in attributes inspector

Plow Is Add Button to Off. Then modify 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). It looks similar this:

change fill color and is add button properties

The changes will take identify in your storyboard:

minus button

Pretty cool. Now modify Is Add Button back to On to render the button to a plus button.

Adding a 2nd Push button

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

Identity Inspector Push Button

Change its grade to PushButton as you did it with previous 1. You'll see a light-green plus push button nether your sometime 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 Push button.

Add together the Auto Layout constraints for the new view. It's similar 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 push. Then choose Width from the popular-upwardly menu.
  • With the button selected, Control-drag from the center of the button slightly up while staying inside the button. Choose Height from the popular-up menu.
  • Control-elevate left from within the push to outside the button. Choose Eye Horizontally in Container.
  • Control-drag upwards from the bottom button to the acme button. Cull Vertical Spacing.

Afterwards 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 now have a reusable customizable view that yous tin add to whatever app. It'due south besides well-baked and sharp on any size device.

Calculation Arcs with UIBezierPath

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

counter view

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

Create a new file by selecting FileNewFile…. Then choose Cocoa Touch Grade, and name the new form CounterView. Make information technology a subclass of UIView and ensure the language is Swift. Click Next, and then click Create.

Supervene upon the code with:

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

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

Y'all also created 3 @IBInspectable properties that you lot can update in the storyboard. counter keeps rail of the number of glasses consumed. It'due south an @IBDesignable property because it is useful to have the ability to change it in the storyboard, especially for testing the counter view.

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

  1. With the view selected, Control-elevate from the middle of the button slightly left while staying within the view. Cull Width from the pop-up menu.
  2. Similarly, with the view selected, Control-drag from the eye of the push button slightly up while staying within the view. Cull Top from the pop-up menu.
  3. Control-elevate left from inside the view to exterior the view. Choose Heart Horizontally in Container.
  4. Command-elevate down from the view to the top button. Cull Vertical Spacing.

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

edit constants in size inspector

In the Identity inspector, change the class of the UIView to CounterView. Whatsoever cartoon that you code in draw(_:) will now appear in the view. But you oasis't added any…yet!

Enjoying an Impromptu Math Lesson

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

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

high school level math

The blood-red arrow shows where your arc will start and cease, drawing in a clockwise direction. You'll describe an arc from the position 3π/4 radians — that's the equivalent of 135º — clockwise to π/iv radians — that's 45º.

Radians are generally used in programming instead of degrees, and thinking in radians means you won't take to convert to degrees every time you piece of work with circles. Heads upwards: You'll need to figure out the arc length later, and radians will come into play then.

An arc's length in a unit circumvolve with a radius of 1.0 is the same as the bending'southward measurement in radians. Looking at the diagram in a higher place, for case, the length of the arc from 0º to 90º is π/ii. To summate the length of the arc in a real state of affairs, take the unit circle arc length and multiply it by the actual radius.

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

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

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

a heart-emoji for math

Returning to Arcs

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

// 1 let center = CGPoint(ten: bounds.width / 2, y: bounds.height / 2)  // 2 let radius = max(bounds.width, bounds.height)  // 3 permit startAngle: CGFloat = 3 * .pi / 4 let endAngle: CGFloat = .pi / 4  // 4 let path = UIBezierPath(   arcCenter: eye,   radius: radius/2 - 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. Define the center point yous'll rotate the arc around.
  2. Calculate the radius based on the maximum dimension of the view.
  3. Ascertain the start and terminate angles for the arc.
  4. Create a path based on the center point, radius and angles you defined.
  5. Set the line width and color earlier finally stroking the path.

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

In this code, eye is the signal 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 want to dive farther into this topic, and so Core Graphics Tutorial on Arcs and Paths will help.

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

screen with an arc and plus and minus buttons

Outlining the Arc

When you bespeak you lot've enjoyed a cool glass of water, an outline on the counter will testify you your progress toward the eight-glass goal. This outline volition 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  //ane - first summate the divergence betwixt the two angles //ensuring it is positive permit angleDifference: CGFloat = 2 * .pi - startAngle + endAngle //then calculate the arc for each single glass let arcLengthPerGlass = angleDifference / CGFloat(Constants.numberOfGlasses) //and so multiply out past the actual glasses drunk let outlineEndAngle = arcLengthPerGlass * CGFloat(counter) + startAngle  //ii - draw the outer arc allow outerArcRadius = bounds.width/2 - Constants.halfOfLineWidth allow outlinePath = UIBezierPath(   arcCenter: centre,   radius: outerArcRadius,   startAngle: startAngle,   endAngle: outlineEndAngle,   clockwise: true)  //3 - draw the inner arc let innerArcRadius = premises.width/2 - Constants.arcWidth   + Constants.halfOfLineWidth  outlinePath.addArc(   withCenter: center,   radius: innerArcRadius,   startAngle: outlineEndAngle,   endAngle: startAngle,   clockwise: false)      //4 - close the path outlinePath.shut()      outlineColor.setStroke() outlinePath.lineWidth = Constants.lineWidth outlinePath.stroke()        

A few things to get through here:

  1. outlineEndAngle is the bending where the arc should terminate; 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 non a unit circle.
  3. Adds an inner arc to the start arc. It has the same angles just draws in contrary. That'southward why clockwise was set to false. Also, this draws a line between 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 set to 5, your CounterView volition look similar this in the storyboard:

view counter view

Open Main.storyboard and select CounterView. In the Attributes inspector, change Counter to check out your drawing code. You'll find information technology is completely interactive. Experiment by adjusting the counter to be more than eight and less than zero.

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

change counter color and outline color

Making it All Work

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

In Main.storyboard, drag a UILabel to the center of Counter View. Brand certain it is a subview of Counter View. Add constraints to center the label vertically and horizontally. When you cease, it will take constraints that look like this:

add constraints to label

In the Attributes inspector, change Alignment to middle, font size to 36 and the default label title to 8.

change properties in attributes inspector

Go to ViewController.swift and add these properties to the elevation 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 stop of the form:

@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 you lot could set the counter to fewer than zero, it probably won't work with Flo. Nobody can drinkable negative water. :]

Y'all also updated the counter value in the label.

Next, add this lawmaking 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 Touch on Up Within event of the two PushButtons.

view controller's IBOutlet and IBAction connected to storyboard

Build and run.

See if your buttons update the counter label. They should. But y'all may notice the counter view isn't updating. Think way back to the commencement of this tutorial. Remember, yous only called describe(_:) when other views on top of it moved, its hidden belongings 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 belongings 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 just when the counter is less than or equal to the user'due south 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 Hither?

You tin download the completed version of the projection using the Download Materials push at the elevation or bottom of this tutorial.

Amazing! You've covered basic drawing in this tutorial. You lot tin can now change the shape of views in your UIs. But expect — there'south more!

In Role 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 similar to learn more almost custom layouts, consider the post-obit resources:

  • Check out this folio with list of resources provided past Apple tree.
  • Follow our video class on Cadre Graphics if you prefer the video format.

If you have whatever questions or comments, please join the forum discussion beneath.

sherercaph1941.blogspot.com

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

0 Response to "How to Draw a Circle in Xcode Storyboard"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel