21

I have a UILabel in UITableView. Here is the code i have written in cellForRowAtIndexPath

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectMake(30.0, 5.0, 250.0, 35.0) reuseIdentifier:CellIdentifier] autorelease];
    }   


    CGRect rect = CGRectMake(30.0, 5.0, 250.0, 35.0);
    UILabel *label = [[UILabel alloc] initWithFrame:rect];

    label.opaque = NO;  
    label.font = [UIFont systemFontOfSize:14];
    label.numberOfLines = 2;
    label.textAlignment = UITextAlignmentCenter;            
    label.textColor = [UIColor darkGrayColor];
    label.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0];
    [label setText:@"Test Message"];    

    [cell addSubview:label];
    [label release];
    cell.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;    

My intention was to set the background of cell and UILabel as transparent.

But it is not working. can any one tell me what i am missing here

Thanks

Sandeep

Vladimir
  • 170,431
  • 36
  • 387
  • 313
user270520
  • 211
  • 1
  • 2
  • 5

3 Answers3

74

Change the following line:

label.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0];

to this:

label.backgroundColor = [UIColor clearColor];
Florin
  • 1,844
  • 2
  • 16
  • 21
oden
  • 3,461
  • 1
  • 31
  • 33
  • Now that you've pointed us in the right direction (thanks!) I'll add that `label.backgroundColor = nil;` is easier to remember and does the same thing. (BG color is a property of the superclass, UIView. Per class ref, "The default value is nil, which results in a transparent background color." The UILabel subclass probably sets it to white initially, which is why you have to explicitly change it back to nil/clear.) – Wienke Sep 27 '12 at 15:13
  • 1
    Upon testing, however, it turns out you should stick with oden's original answer. Nullifying the backgroundColor works fine at first, but if you subsequently change the label's text, the new text will be *superimposed* on the old. Very weird. – Wienke Sep 27 '12 at 19:50
  • Setting the value to nil was my first guess as well, but it resulted in the entire label (text and background) turning completely black. [UIColor clearColor] worked perfectly. – Greg Brown May 16 '13 at 00:45
  • For swift 2.3 use `label.backgroundColor = UIColor.clearColor() ` – Xaren Nov 10 '16 at 18:58
2

For those using Xamarin.iOS it's obviously:

UILabel myLabel = new UILabel();
myLabel.Text = "Hello world!";
myLabel.BackgroundColor = UIColor.Clear;
Miros
  • 527
  • 1
  • 3
  • 11
1
[label setBackGroundColor:[UIColor clearColor]];

To set the clearBackGround Color for a label