Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a round cornered UILabel on the iPhone?

Is there a built in way to create round-cornered UILabels? If the answer is no, how would one go about creating such an object?

like image 271
newtonapple Avatar asked Feb 04 '09 07:02

newtonapple


People also ask

How do you round UIView corners?

If you start with a regular UIView it has square corners. You can give it round corners by changing the cornerRadius property of the view's layer . and smaller values give less rounded corners. Both clipsToBounds and masksToBounds are equivalent.

How do I create a rounded label in Swift?

"label. layer. masksToBounds = true" is an important code, if you apply corner radius to a label and if it dosen't work than adding this will definitely add the corner radius to a particular label.. So this should be the correct answer..

What is corner radius?

The corner radius is a measurement describing the curve on the corners of your labels. This is measured in millimetres and refers to the radius of the circle created if the curve was extended to create a full circle.


2 Answers

iOS 3.0 and later

iPhone OS 3.0 and later supports the cornerRadius property on the CALayer class. Every view has a CALayer instance that you can manipulate. This means you can get rounded corners in one line:

view.layer.cornerRadius = 8; 

You will need to #import <QuartzCore/QuartzCore.h> and link to the QuartzCore framework to get access to CALayer's headers and properties.

Before iOS 3.0

One way to do it, which I used recently, is to create a UIView subclass which simply draws a rounded rectangle, and then make the UILabel or, in my case, UITextView, a subview inside of it. Specifically:

  1. Create a UIView subclass and name it something like RoundRectView.
  2. In RoundRectView's drawRect: method, draw a path around the bounds of the view using Core Graphics calls like CGContextAddLineToPoint() for the edges and and CGContextAddArcToPoint() for the rounded corners.
  3. Create a UILabel instance and make it a subview of the RoundRectView.
  4. Set the frame of the label to be a few pixels inset of the RoundRectView's bounds. (For example, label.frame = CGRectInset(roundRectView.bounds, 8, 8);)

You can place the RoundRectView on a view using Interface Builder if you create a generic UIView and then change its class using the inspector. You won't see the rectangle until you compile and run your app, but at least you'll be able to place the subview and connect it to outlets or actions if needed.

like image 156
benzado Avatar answered Sep 18 '22 01:09

benzado


For devices with iOS 7.1 or later, you need to add:

yourUILabel.layer.masksToBounds = YES; yourUILabel.layer.cornerRadius = 8.0; 
like image 29
OscarWyck Avatar answered Sep 19 '22 01:09

OscarWyck