3

以编程方式创建多行 UILabel、将其添加到 UIView 并将 UIView 添加到视图控制器以便在方向更改时正确调整大小的最佳方法是什么?

我看到以前曾多次提出过类似的问题,但我没有找到针对我的特定情况的任何解决方案。我有一个视图,我正在尝试添加一个多行 UILabel。我提出的代码添加了标签,但它始终是横向模式下视图的宽度。旋转 iPad 会导致整个应用程序按预期旋转,除了 UILabel 太宽。我确信答案在于某种组合的.autoresizingMaskor .sizeToFitor.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但我已经在墙上撞了几天,所以我觉得我已经尝试了一切。任何建议,将不胜感激。

4

1 回答 1

3

只需添加:

[content setAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleRightMargin];

当你说:

setContentMode:,你只是告诉视图如何在边界改变时调整子视图的大小,但是,边界没有改变!(因为缺少自动调整大小的掩码标志)

如果 vc 是从 NIB 加载的 viewController ,请从 NIB 文件中仔细检查其视图的自动调整大小选项,否则,也向其添加自动调整大小掩码标志。

于 2012-07-15T13:37:57.157 回答