UITextView with Rounded Corners and Colored Border

In a previous post, Add Rounded Corners and Border to UIWebview, I wrote a few lines of code to add rounded corners and a border color to a webview. A few people have inquired if this is also possible on a UITextView, the answer is yes, and it’s equally as easy to code.

The image below shows a UITextView with rounded corners, the code follows:

I began with a simple view controller and one textview instance variable:

@interface TestViewController : UIViewController
{
  UITextView  *textViewStatus;
}

In the loadview method, I setup the view and create an instance of a textview. I follow this by setting the background color, font, aligning the text and toggling editable to off.

Lines 13-16 define the border color, width and the corner radius. Notice the code in this section references the Core Animation layer of the textview, which is the key to futzing with the radius.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
- (void)loadView 
{
  [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
  [[self view] setBackgroundColor:[UIColor colorWithRed:0.0 green:.34 blue:.74 alpha:1]];
 
  textViewStatus = [[UITextView alloc] initWithFrame:CGRectMake	(20, 20, 280, 40)];
  [textViewStatus setBackgroundColor:[UIColor lightGrayColor]];
  [textViewStatus setFont:[UIFont boldSystemFontOfSize:16.0]];
  [textViewStatus setTextAlignment:UITextAlignmentCenter];
  [textViewStatus setEditable:NO];
 
  // For the border and rounded corners
  [[textViewStatus layer] setBorderColor:[[UIColor whiteColor] CGColor]];
  [[textViewStatus layer] setBorderWidth:2.3];
  [[textViewStatus layer] setCornerRadius:15];
  [textViewStatus setClipsToBounds: YES];
 
  [textViewStatus setText:@"iOSDeveloperTips.com"];
 
  [[self view] addSubview:textViewStatus];
}
Download Source Code

Xcode Project – Round Corners on UITextView

  1. Thanks for your post.

    I’ve got a Question.
    What version of xCode do you use?

    mine version keeps complaining about : setBorderColor method not found. same for setBorderWidth and setCornerRadius.
    after build and run, the textview doesn’t do as i expect. no round corners no blue border…

    • The methods are only available in iPhone OS 3+, make sure you have the build settings to target 3+ or greater.

  2. @John: Thanks for the tip! This is really useful to create rounded UIViews. Too bad corner roundness cannot be changed in Interface Builder.

    @Ronald: Looks like you don’t have Quartz framework added to your project. You need to add QuartzCore framework and add #import (or was it /QuartzCore.h>) line to the .m file.

  3. This does not work with xcode 4.2 I guess
    If it is so,
    can you please tell me how.

  4. importing QuartzCore/QuartzCore.h
    worked for me to solve “setBorderColor method not found ” warning.

  5. importing into my header .h file also worked for me. Cheers.

Comments are closed.