Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing border in UILabel

Well, I have some problems with border drawing in UILabel. Here is my snippet of code

CGRect frame = CGRectMake(10, 10, 320, 120);
UILabel *label = [[UILabel alloc] initWithFrame:frame];
label.textColor = [UIColor greenColor];
label.font = [UIFont fontWithName:@"Verdana" size:12];
label.textAlignment = UITextAlignmentCenter;
label.text = @"Some text to display"; 
label.layer.backgroundColor = [UIColor cyanColor].CGColor;
label.layer.borderColor = [UIColor redColor].CGColor;
[self.window addSubview:label];
[label release];label=nil;

I have QuartzCore included and I use iOS4.3 When I launch the app in sumulator text is displayed but not the border and background color. What is wrong here ?

like image 432
objlv Avatar asked Jul 27 '26 04:07

objlv


2 Answers

Looking in CALayer.h, we see that the default value for borderWidth is 0.0.

/* The width of the layer's border, inset from the layer bounds. The
 * border is composited above the layer's content and sublayers and
 * includes the effects of the `cornerRadius' property. Defaults to
 * zero. Animatable. */

@property CGFloat borderWidth;

In order for the border to appear, you must set the borderWidth to something greater than zero.

You can set the background color on the label directly as so:

label.backgroundColor = [UIColor cyanColor];

To set a border, you need to set the width, which can be done like so:

label.layer.borderWidth = 2.0f;

Once you have set a border width, to set the color of the border on the label, you're setting the view's layer's border, which uses a CGColor, so you'll have to do this:

label.layer.borderColor = [UIColor redColor].CGColor;

And if you want to round the corners, you can add this:

label.layer.cornerRadius = 10.0f;

You don't need to set the background color. You really need to only set the borderWidth and borderColor.

like image 128
Stephen Poletto Avatar answered Jul 29 '26 21:07

Stephen Poletto


label.layer.borderColor = [UIColor darkGrayColor].CGColor;
label.layer.borderWidth = 1.0;
like image 44
Nithin M Keloth Avatar answered Jul 29 '26 21:07

Nithin M Keloth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!