我正在尝试添加大小可变的 UILabel。
标签包含来自用户的评论。我在这里尝试实现标签的动态大小,然后将它们添加到我的视图中(稍后我将添加到主视图中)
我知道这会使标签出现在彼此之上,但这不是问题。标签根本不显示。
NSMutableDictionary *comments = [[NSMutableDictionary alloc] init];
[comments setObject:@"xxxxxxxxx" forKey:@"simon"];
[comments setObject:@"xxxxxxxxxxxxxxxx" forKey:@"pontus"];
[comments setObject:@"xxxxx" forKey:@"sudden"];
[comments setObject:@"xxxx" forKey:@"juan"];
[comments setObject:@"xxxxxxxxxxx" forKey:@"eric"];
DetailedViewController *detailedBurger= [[DetailedViewController alloc] initWithNibName:nil bundle:nil];
for(NSString *key in comments){
UILabel *label = [[UILabel alloc] init];
label.backgroundColor = [UIColor clearColor];
label.text = [comments objectForKey:key]; //etc...
[label setFont:[UIFont fontWithName:@"PatuaOne-Regular" size:12.0]];
CGSize maximumLabelSize = CGSizeMake(296,9999);
CGSize expectedLabelSize = [label.text sizeWithFont:label.font
constrainedToSize:maximumLabelSize
lineBreakMode:label.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = label.frame;
newFrame.size.height = expectedLabelSize.height;
newFrame.size.width = expectedLabelSize.width;
NSLog(@"expectedlabelsizeheight %f", newFrame.size.height);
label.frame = newFrame;
[label setNeedsDisplay];
[detailedBurger.commentField addSubview:label];
NSLog(@"%f, %f", label.center.x, label.center.y);
}
// Do any additional setup after loading the view from its nib.
self.backgroundView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]];
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.backgroundView.frame];
scrollView.contentSize = CGSizeMake(320, 900);
[scrollView addSubview:detailedBurger.view];
detailedBurger.view.center = CGPointMake(160, detailedBurger.view.frame.size.height/2);
[self.backgroundView addSubview:scrollView];
如果我用硬值(例如label.frame = CGRectMake(0,0,10,10)
)明确设置框架,则此代码有效,但动态调整大小似乎不起作用。
控制台输出:
2013-07-09 10:12:42.223 RateYourBurger[31439:c07] expectedlabelsizeheight 15.000000
2013-07-09 10:12:42.224 RateYourBurger[31439:c07] 10.000000, 20.000000
2013-07-09 10:12:42.224 RateYourBurger[31439:c07] expectedlabelsizeheight 15.000000
2013-07-09 10:12:42.224 RateYourBurger[31439:c07] 10.000000, 20.000000
2013-07-09 10:12:42.225 RateYourBurger[31439:c07] expectedlabelsizeheight 15.000000
2013-07-09 10:12:42.225 RateYourBurger[31439:c07] 10.000000, 20.000000
2013-07-09 10:12:42.226 RateYourBurger[31439:c07] expectedlabelsizeheight 15.000000
2013-07-09 10:12:42.226 RateYourBurger[31439:c07] 10.000000, 20.000000
2013-07-09 10:12:42.227 RateYourBurger[31439:c07] expectedlabelsizeheight 15.000000
2013-07-09 10:12:42.227 RateYourBurger[31439:c07] 10.000000, 20.000000