tags:

views:

27

answers:

1

Hi,

I want to dynamically assign width to a label depending upon the text length to be displayed. The labels are it self being added on uiview. I am using following code but still i am getting label with shorter width.

- (id)initWithFrame:(CGRect)frame OrangeText:(NSString*)orange WhiteText:(NSString*)white {
if ((self = [super initWithFrame:frame])) {
    CGSize textSize = [orange sizeWithFont:[UIFont systemFontOfSize:14]];
    OrangeLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, textSize.width, textSize.height+2)];
    OrangeLabel.text = orange;
    OrangeLabel.backgroundColor = [UIColor clearColor];
    OrangeLabel.textColor = [UIColor orangeColor];
    [self addSubview:OrangeLabel];

    WhiteLabel = [[UILabel alloc] init];
    CGSize whiteTextSize = [white sizeWithFont:[UIFont systemFontOfSize:14]];
    WhiteLabel.frame = CGRectMake(OrangeLabel.frame.size.width+35, 5, whiteTextSize.width, whiteTextSize.height);
    WhiteLabel.text = white;
    WhiteLabel.backgroundColor = [UIColor clearColor];
    WhiteLabel.textColor = [UIColor whiteColor];
    [self addSubview:WhiteLabel];        // Initialization code
}
return self;

}

+4  A: 

I think you are looking for this method

[myLabel sizeToFit];

This should resize the label frame to fit its contents.

Bongeh
thanks it helped..
pankaj