2010-10-18 61 views
0

我想根据要显示的文本长度动态地将宽度分配给标签。标签是它自己被添加到uiview。我正在使用下面的代码,但我仍然得到较短宽度的标签。动态增加uilabel的宽度

- (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; 

}

回答

6

我认为你正在寻找这种方法

[myLabel sizeToFit];

这应该调整标签框架,以适应其内容。

+0

感谢它帮助.. – pankaj 2010-10-18 11:13:22