2010-10-18 101 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