2011-02-02 26 views
0

我想創建一個適合他內容的UIView。內容是帶有動態文本的UILabel。根據內容適應高度的UIView - Objective-c

UIView *myview = [ [UIView alloc ] initWithFrame:CGRectMake(10.0, 10.0, 700.0, 100.0)]; 
myview.backgroundColor = [UIColor redColor]; 

[self.view addSubview:myview]; 

UILabel *myLabel = [ [UILabel alloc ] initWithFrame:CGRectMake(10.0, 10.0, 500.0, 43.0) ]; 
myLabel.textAlignment = UITextAlignmentLeft; 
myLabel.textColor = [UIColor whiteColor]; 
myLabel.backgroundColor = [UIColor blackColor]; 
myLabel.font = [UIFont fontWithName:@"Arial Rounded MT Bold" size:(36.0)]; 
[myView addSubview:myLabel]; 
myLabel.numberOfLines = 0; 
myLabel.text = @"This is an UILabel. This is an UILabel. This is an UILabel. This is an UILabel. This is an UILabel. This is an UILabel. This is an UILabel. "; 
[myLabel sizeToFit]; 

我附上截圖:

Screenshot

回答

3

[myLabel sizeToFit]後試試這個:

[myView setFrame:myLabel.frame]; 
+0

差不多!這沒關係,但它不能保證保證金。看看:http://i54.tinypic.com/15gpmy8.png – HispaJavi 2011-02-02 12:10:12

0

這將這樣的伎倆:

NSString *tempString = @"This is an UILabel. This is an UILabel. This is an UILabel. This is an UILabel. This is an UILabel. This is an UILabel. This is an UILabel. "; 

    CGSize constSize = { 260.0f, 20000.0f }; 

CGSize textSizeTitle = [tempString sizeWithFont:[UIFont systemFontOfSize:20.0] constrainedToSize:constSize lineBreakMode:UILineBreakModeWordWrap]; 

UILabel *EventTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 260,textSizeTitle.height)]; 
[EventTitle setText:tempString]; 
[EventTitle setBackgroundColor:[UIColor clearColor]]; 
[EventTitle setFont:[UIFont fontWithName:@"TrebuchetMS-Bold" size:20]]; 
[EventTitle setNumberOfLines:0]; 
[EventTitle setUserInteractionEnabled:NO]; 
[EventTitle setTextColor:[UIColor whiteColor]]; 
[newsBox addSubview:EventTitle]; 

只需確保,textSizeTitle的字體大小& EventTitle應該相同。

相關問題