以编程方式创建多行UILabel的最佳方法是什么,将其添加到UIView,并将该UIView添加到视图控制器,以便在方向更改时正确调整大小?
我发现以前曾多次提出过类似的问题,但我找不到任何解决方案。我有一个观点,我正在尝试添加多行UILabel。我提出的代码添加了标签,但它始终是横向模式下视图的宽度。旋转iPad导致整个应用程序按预期旋转,除了UILabel太宽。我确定答案取决于某些组合中的.autoresizingMask
或.sizeToFit
或.autoresizesSubviews
属性,但到目前为止我还没有得到它。这是我的代码
UIViewController *vc = [[UIViewController alloc] init];
vc.title = @"Welcome";
// tbc is an instance of the tab bar controller that this view will go into
UILabel *copy = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tbc.view.frame.size.width, MAXFLOAT)];
NSString *copyText = @"Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Cras mattis consectetur purus sit amet fermentum. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Cras mattis consectetur purus sit amet fermentum. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.";
UIFont *copyFont = [UIFont fontWithName:@"HoeflerText-Regular" size:20.0f];
[copy setContentMode:UIViewContentModeScaleAspectFit];
[copy setText:copyText];
[copy setFont:copyFont];
[copy setNumberOfLines:0];
[copy setLineBreakMode:UILineBreakModeWordWrap];
[copy setAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleRightMargin];
CGRect frame = copy.frame;
frame.origin.x = 50;
frame.origin.y = 100;
frame.size.width = tbc.view.frame.size.width;
frame.size.height = tbc.view.frame.size.height - 100;
[copy setFrame:frame];
[copy sizeToFit];
UIView *content = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tbc.view.frame.size.width, vc.view.frame.size.height)];
[content setAutoresizesSubviews:YES];
[content addSubview:copy];
[content sizeToFit];
[vc.view setAutoresizesSubviews:YES];
[vc.view setContentMode:UIViewContentModeScaleAspectFit];
[vc.view addSubview:content];
正如我所说,我确定我错过了.autoresizeMask
的某些内容,但我已经在这上面撞墙了几天,所以我觉得我已经尝试过了一切。任何建议将不胜感激。
答案 0 :(得分:3)
只需添加:
[content setAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleRightMargin];
当你说:
setContentMode:
,您只是告诉视图如何调整子视图的大小如果边界发生变化,但是边界不会改变!! (因为缺少自动调整掩码标志)
如果vc是从NIB加载的viewController,请从NIB文件中仔细检查它的自动查看选项,否则,也要为其添加自动调整掩码标记。