Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I programmatically set the background color of a UILabel?

I'm diving into iOS development and I'm programmatically creating some labels, but I can't seem to set their background color to black. From what I read, it seems simple enough, here's my code...

UILabel *lbl = [[[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height] autorelease];
[[lbl layer] setBorderColor:[[UIColor blackColor] CGColor]];
[[lbl layer] setBorderWidth:1.0];
[[lbl layer] setBackgroundColor:[[UIColor blackColor] CGColor]];
[[self view] addSubview:lbl];

When I do this, the border color and width work as expected, but the background color remains white. Am I forgetting to do something?

Thanks so much for your help!

like image 508
BeachRunnerFred Avatar asked Oct 29 '10 17:10

BeachRunnerFred


People also ask

How do I change the background color in Xcode?

At the top select the attributes inspector. Under the section "View" there should be a spot that says "Background". click that and choose your colour.

How do you change the background color of a Uibutton in Swift?

Method 1 − Using the storyboard editorAdd a button on your storyboard, select it Go to it's attribute inspector and select 'Background' property to choose the color.

How do you change the color of a label in Xcode?

There should be a text color box in interface builder, but you can also do it through code. UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,100,100)] label. textColor = [UIColor redColor]; Or just use the reference that you already have to the text label.


1 Answers

A UILabel already has a .backgroundColor property, you don't need to tweak its layer...

lbl.backgroundColor = [UIColor blackColor];
like image 137
kennytm Avatar answered Oct 30 '22 10:10

kennytm