2011-02-02 3 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

+0

И я думаю, что это не будет решением, потому что мне нужно будет поставить еще один ярлык ниже этого. – HispaJavi

+0

Хорошо, я сделал это. Спасибо. – HispaJavi

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 должен быть таким же.