Giving UIView rounded corners
Asked Answered
K

21

614

My login view has a subview which has a UIActivityView and a UILabel saying "Signing In…". This subview has corners which aren't rounded. How can I make them round?

Is there any way to do it inside my xib?

Kinky answered 2/10, 2009 at 13:36 Comment(3)
Doing something like this in IB would require a pre-rendered image with rounded cornersIrritable
Not necessarily @ed-marty, This answer from @Gujamin deserves some more credit as it shows how to apply the cornerRadius property to the table using Interface Builder only, without having to use either pre-rendered images or set it in the code.Knickerbockers
from @S.P. iphonedevsdk.com/forum/tutorial-requests/…Manatarms
I
1270

Try this

#import <QuartzCore/QuartzCore.h> // not necessary for 10 years now  :)

...

view.layer.cornerRadius = 5;
view.layer.masksToBounds = true;

Note: If you are trying to apply rounded corners to a UIViewController's view, it should not be applied in the view controller's constructor, but rather in -viewDidLoad, after view is actually instantiated.

Irritable answered 2/10, 2009 at 13:40 Comment(16)
Note that property only exists in iPhone 3.0, not earlier versions.Scintillometer
I just have to say that this was one of the most immediately satisfying answers I've ever seen on SO. Checking here first just saved me an hour of fighting with an image editor and would have made my view more brittle to color / sizing changes. Thanks!Tatterdemalion
Related note: anyone interested in more visual goodies (i.e. shadow) to easily apply to a UIView should check out the CALayer class reference. Most of it is as easy as setting one or two property values, like the above answer: developer.apple.com/mac/library/documentation/GraphicsImaging/…Tatterdemalion
I have tried this on a view that was loaded from a nib file, and it didn't work. pastie.org/964695Sticky
see this link cocoabugs.blogspot.com/2010/08/…Evaginate
@Ben Collins (or anyone else who has this problem), make sure your view has "clip subviews" set. You can check this in interface builder.Hyphen
this works great BUT if you have a lot of these rounded corners in any sort of scroll view or animation (I tried using them in a UITableView) you performance will suffer greatly. Nice smooth scrolling table view quickly become choppy :(Gause
@EdMarty please edit your answer to include the Quartz import and the setMasksToBounds. Long comment threads are anathema to Stackoverflow.Kathiekathleen
@Gause : Do you know a trick to get a nice smooth scrolling - along with some rounded corners?Graves
doesn't seem to work in the constructor, but works fine in viewDidLoadAgraphia
@NerujaJoseph the only way I could get good performance was to fake rounded corners by using background images that had rounded corners.Gause
@Gause I actually got something to work but performance still suffers a little - not much (God thanks). Look here on this linkGraves
Minimal changes on Swift: view.layer.cornerRadius = 5 view.layer.masksToBounds = trueRunofthemill
in Swift4 and XCode 9 it seems to work fine without view.layer.masksToBounds = true. Sorry about stupid question, but why is that?Peruke
That property is to make sure that any child content doesn’t draw outside the rounded corners.Irritable
Also, some types of UIView subclasses already have that property turned on by default.Irritable
B
277

You can also use the User Defined Runtime Attributes feature of interface builder to set the key path layer.cornerRadius to a value. Make sure you include the QuartzCore library though.

This trick also works for setting layer.borderWidth however it will not work for layer.borderColor as this expects a CGColor not a UIColor.

You will not be able to see the effects in the storyboard because these parameters are evaluated at runtime.

Using Interface builder to set the corner radius

Barrera answered 15/7, 2012 at 22:17 Comment(4)
remember to check the Clip Subviews option in for the view IB as wellScrimp
(or) add a Key Path: layer.masksToBounds, Type: boolean: CheckedEdgardoedge
Set the 2 user defined runtime attributes (layer.cornerRadius and layer.masksToBounds) on the FxView in the document outline, not on its view. This answer is a lifesaver! Works for me using Xcode 12.3, without the #import <QuartzCore/QuartzCore.h> statement.Antimere
In Xcode 12.4 the setting to clip subviews can be found in the "Attributes inspector": It's a tickbox in the "Drawing" section and it's called "Clips to Bounds".Literalism
D
78

Swift

Short answer:

myView.layer.cornerRadius = 8
myView.layer.masksToBounds = true  // optional

Supplemental Answer

If you have come to this answer, you have probably already seen enough to solve your problem. I'm adding this answer to give a bit more visual explanation for why things do what they do.

If you start with a regular UIView it has square corners.

let blueView = UIView()
blueView.frame = CGRect(x: 100, y: 100, width: 100, height: 50)
blueView.backgroundColor = UIColor.blueColor()
view.addSubview(blueView)

enter image description here

You can give it round corners by changing the cornerRadius property of the view's layer.

blueView.layer.cornerRadius = 8

enter image description here

Larger radius values give more rounded corners

blueView.layer.cornerRadius = 25

enter image description here

and smaller values give less rounded corners.

blueView.layer.cornerRadius = 3

enter image description here

This might be enough to solve your problem right there. However, sometimes a view can have a subview or a sublayer that goes outside of the view's bounds. For example, if I were to add a subview like this

let mySubView = UIView()
mySubView.frame = CGRect(x: 20, y: 20, width: 100, height: 100)
mySubView.backgroundColor = UIColor.redColor()
blueView.addSubview(mySubView)

or if I were to add a sublayer like this

let mySubLayer = CALayer()
mySubLayer.frame = CGRect(x: 20, y: 20, width: 100, height: 100)
mySubLayer.backgroundColor = UIColor.redColor().CGColor
blueView.layer.addSublayer(mySubLayer)

Then I would end up with

enter image description here

Now, if I don't want things hanging outside of the bounds, I can do this

blueView.clipsToBounds = true

or this

blueView.layer.masksToBounds = true

which gives this result:

enter image description here

Both clipsToBounds and masksToBounds are equivalent. It is just that the first is used with UIView and the second is used with CALayer.

See also

Drama answered 25/1, 2016 at 1:7 Comment(1)
I would also like to add that setting the corner radius to half of the shorter side (in this case blueView.frame.size.height/2) results in a perfectly rounded corner.Christinachristine
C
66

Now you can use a swift category in UIView (code bellow the picture) in with @IBInspectable to show the result at the storyboard (If you are using the category, use only cornerRadius and not layer.cornerRadius as a key path.

extension UIView {
    @IBInspectable var cornerRadius: CGFloat {
        get {
            return layer.cornerRadius
        }
        set {
            layer.cornerRadius = newValue
            layer.masksToBounds = newValue > 0
        }
    }
}

enter image description here

Carryingon answered 16/1, 2014 at 16:26 Comment(2)
And if you're using a custom sub-class, Make sure to tag it with @IBDesignable to get a live preview in IB! (More at nshipster.com/ibinspectable-ibdesignable)Brachium
This doesn't seem to work in current XCode. The view is rounded running on the device but not in IB.Calabrese
T
44

A different approach than the one Ed Marty did:

#import <QuartzCore/QuartzCore.h>

[v.layer setCornerRadius:25.0f];
[v.layer setMasksToBounds:YES];

You need the setMasksToBounds for it to load all the objects from IB... i got a problem where my view got rounded, but did not have the objects from IB :/

this fixed it =D hope it helps!

Terrie answered 9/12, 2010 at 12:23 Comment(3)
how is it different? other than not using dot syntax?Pluckless
[v.layer setMasksToBounds:YES]; \n this line is magic, it solves my big problemTratner
I wrote this when i started iOS development and didn't know there wasn't a difference between dot syntax and the bracket syntax. Therefore I wrote it as "different". My code also included the import<> that Ed Marty did not have in his original response (later edited in) and therefore my answer help people fix their problem (aka not having it imported).Terrie
H
28

As described in this blog post, here is a method to round the corners of a UIView:

+(void)roundView:(UIView *)view onCorner:(UIRectCorner)rectCorner radius:(float)radius
{
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds
                                                   byRoundingCorners:rectCorner
                                                         cornerRadii:CGSizeMake(radius, radius)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    [view.layer setMask:maskLayer];
    [maskLayer release];
}

The cool part about it is that you can select which corners you want rounded up.

Halleyhalli answered 10/9, 2012 at 11:9 Comment(3)
Rather than just providing a link to an external site, we prefer that answers be self-contained here, so I brought the relevant code from the linked blog post into your answer. People can visit the blog post for more detail, but this make sure that the content will survive if the post in question goes away. Also, you posted this answer to several different questions that didn't really ask the same thing. Those were removed, and one question was closed as a duplicate of this one. We like to have answers crafted to match each question.Meridel
Prescient. The blog post is 404 now.Impractical
This approach is Clean but it will hide any shadow effect on the view.Protease
H
22

You can use following custom UIView class which can also change border color and width. As this is IBDesignalbe You can change the attributes in interface builder as well.

enter image description here

import UIKit

@IBDesignable public class RoundedView: UIView {

    @IBInspectable var borderColor: UIColor = UIColor.white {
        didSet {
            layer.borderColor = borderColor.cgColor
        }
    }

    @IBInspectable var borderWidth: CGFloat = 2.0 {
        didSet {
            layer.borderWidth = borderWidth
        }
    }

    @IBInspectable var cornerRadius: CGFloat = 0.0 {
        didSet {
            layer.cornerRadius = cornerRadius
        }
    }

}
Hilton answered 26/10, 2016 at 8:31 Comment(1)
I am quite new to Swift, is there's a Swift version of this?Roz
C
20

You need to first import header file <QuartzCore/QuartzCore.h>

 #import QuartzCore/QuartzCore.h>

[yourView.layer setCornerRadius:8.0f];
yourView.layer.borderColor = [UIColor redColor].CGColor;
yourView.layer.borderWidth = 2.0f;
[yourView.layer setMasksToBounds:YES];

Don't miss to use -setMasksToBounds , otherwise the effect may not be shown.

Crosse answered 1/8, 2012 at 10:19 Comment(3)
Not need to import "QuartzCore/QuartzCore.h"Sassy
Yes you do need to import.Homiletic
@LordZsolt Maybe they changed that with iOS7, but you needn't import QuartzCore anymore.Gobble
P
8
view.layer.cornerRadius = 25
view.layer.masksToBounds = true
Prog answered 16/4, 2018 at 12:10 Comment(0)
S
6
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(20, 50, 200, 200)];

view.layer.backgroundColor = [UIColor whiteColor].CGColor;
view.layer.cornerRadius = 20.0;
view.layer.frame = CGRectInset(v.layer.frame, 20, 20);

view.layer.shadowOffset = CGSizeMake(1, 0);
view.layer.shadowColor = [[UIColor blackColor] CGColor];
view.layer.shadowRadius = 5;
view.layer.shadowOpacity = .25;

[self.view addSubview:view];
[view release];
Somebody answered 23/5, 2012 at 11:51 Comment(1)
Applying setMasksToBounds is important. Setting a background colour and drop shadow is not.Knickerbockers
H
5

- SwiftUI

In SwiftUI, you can use cornerRadius modifier directly on any View you want. For example of this question:

Text("Signing In…")
    .padding(16)
    .background(Color.red)
    .cornerRadius(50)

Preview

Note that there is no more diamond like radius, so even if you set the cornerRadius more than half of the height, it will round smoothly.

Checkout this answer to se how to Round Specific Corners in SwiftUI

Hominoid answered 9/10, 2019 at 19:49 Comment(0)
S
4

if round corner not working in viewDidload() it's better to write code in viewDidLayoutSubview()

-(void)viewDidLayoutSubviews
{
    viewTextfield.layer.cornerRadius = 10.0 ;                                               
    viewTextfield.layer.borderWidth = 1.0f;
    viewTextfield.layer.masksToBounds =  YES;
    viewTextfield.layer.shadowRadius = 5;
    viewTextfield.layer.shadowOpacity = 0.3;
    viewTextfield.clipsToBounds = NO;
    viewTextfield.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
}

Hope this helps!

Serval answered 21/4, 2018 at 6:22 Comment(0)
Z
4

In Swift 4.2 and Xcode 10.1

let myView = UIView()
myView.frame = CGRect(x: 200, y: 200, width: 200, height: 200)
myView.myViewCorners()
//myView.myViewCorners(width: myView.frame.width)//Pass View width
view.addSubview(myView)

extension UIView {
    //If you want only round corners
    func myViewCorners() {
        layer.cornerRadius = 10
        layer.borderWidth = 1.0
        layer.borderColor = UIColor.red.cgColor
        layer.masksToBounds = true
    }
    //If you want complete round shape, enable above comment line
    func myViewCorners(width:CGFloat) {
        layer.cornerRadius = width/2
        layer.borderWidth = 1.0
        layer.borderColor = UIColor.red.cgColor
        layer.masksToBounds = true
    }
}
Zielsdorf answered 1/2, 2019 at 9:59 Comment(0)
U
3

Swift 4 - Using IBDesignable

   @IBDesignable
    class DesignableView: UIView {
    }

    extension UIView
    {

        @IBInspectable
        var cornerRadius: CGFloat {
            get {
                return layer.cornerRadius
            }
            set {
            layer.cornerRadius = newValue
        }
    }
}
Uvula answered 24/10, 2017 at 4:34 Comment(1)
I'm sorry, but as a newcomer to IOS development. How does the solution prevent layer.cornerRadius from being returned to the original state? (e.i. how does xcode's storyboard know how to set cornerRadius only after the original UIView is initialized)?Foist
R
2

Please import Quartzcore framework then you have to set setMaskToBounds to TRUE this the very important line.

Then: [[yourView layer] setCornerRadius:5.0f];

Reisman answered 16/2, 2013 at 9:52 Comment(0)
R
2
UIView* viewWithRoundedCornersSize(float cornerRadius,UIView * original)
{
    // Create a white border with defined width
    original.layer.borderColor = [UIColor yellowColor].CGColor;
    original.layer.borderWidth = 1.5;

    // Set image corner radius
    original.layer.cornerRadius =cornerRadius;

    // To enable corners to be "clipped"
    [original setClipsToBounds:YES];
    return original;
}
Recrystallize answered 2/9, 2014 at 7:48 Comment(0)
S
2

Do this programatically in obj c

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(20, 50,    200, 200)];

view.layer.backgroundColor = [UIColor whiteColor].CGColor;
view.layer.cornerRadius = 20.0;
view.layer.frame = CGRectInset(v.layer.frame, 20, 20);

[view.layer.shadowOffset = CGSizeMake(1, 0);
view.layer.shadowColor = [[UIColor blackColor] CGColor];
view.layer.shadowRadius = 5;
view.layer.shadowOpacity = .25;][1]

[self.view addSubview:view];

We Can Also do this from stoaryboard.

 layer.cornerRadius  Number  5

enter image description here

Subscapular answered 9/2, 2017 at 9:19 Comment(0)
P
1

set cornerRadious Property for round View

set masksToBounds Boolean Value for image will not still be drawn outside the corner radius boundary

view.layer.cornerRadius = 5;

view.layer.masksToBounds = YES;
Praenomen answered 29/12, 2014 at 11:29 Comment(0)
A
0

You can also use an image:

UIImage *maskingImage = [UIImage imageNamed:@"bannerBarBottomMask.png"];
CALayer *maskingLayer = [CALayer layer];
maskingLayer.frame = CGRectMake(-(self.yourView.frame.size.width - self.yourView.frame.size.width) / 2
                                , 0
                                , maskingImage.size.width
                                , maskingImage.size.height);
[maskingLayer setContents:(id)[maskingImage CGImage]];
[self.yourView.layer setMask:maskingLayer];
Aholla answered 24/1, 2013 at 6:59 Comment(0)
M
0

Using UIView Extension:

extension UIView {    

func addRoundedCornerToView(targetView : UIView?)
{
    //UIView Corner Radius
    targetView!.layer.cornerRadius = 5.0;
    targetView!.layer.masksToBounds = true

    //UIView Set up boarder
    targetView!.layer.borderColor = UIColor.yellowColor().CGColor;
    targetView!.layer.borderWidth = 3.0;

    //UIView Drop shadow
    targetView!.layer.shadowColor = UIColor.darkGrayColor().CGColor;
    targetView!.layer.shadowOffset = CGSizeMake(2.0, 2.0)
    targetView!.layer.shadowOpacity = 1.0
}
}

Usage:

override func viewWillAppear(animated: Bool) {

sampleView.addRoundedCornerToView(statusBarView)

}
Marinemarinelli answered 11/5, 2016 at 6:24 Comment(0)
P
-4

ON Xcode 6 Your try

     self.layer.layer.cornerRadius = 5.0f;

or

    self.layer.layer.cornerRadius = 5.0f;
    self.layer.clipsToBounds = YES;
Parallelism answered 28/11, 2014 at 12:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.