如何自动调整UIScrollView的大小

3

我的应用程序中有一个信息页面。由于本地化的不同,文本长度可能会有所不同。除此之外,3.5英寸的屏幕比4英寸的显示器少了一些实际空间。因此,我想要实现的是UILabel在ScrollView内“增长”,并且ScrollView适应屏幕。

这是我的代码:

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

// Create a ScrollView and a label
UIScrollView *infoScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(20.0f, 55.0f, 300.0f, 400.0f)];

CGRect labelFrame = CGRectMake(0, 0, 280, 800);
UILabel *infoLabel = [[UILabel alloc] initWithFrame:labelFrame];

NSString *labelText = NSLocalizedString (@"InfoText",@"");
[infoLabel setText:labelText];

// Tell the label to use an unlimited number of lines
[infoLabel setNumberOfLines:0];
[infoLabel setBackgroundColor:[UIColor clearColor]];
[infoLabel setFont:[UIFont boldSystemFontOfSize:17]];
infoLabel.textColor = [UIColor colorWithRed:255 green:255 blue:255 alpha:1.0];
[infoLabel sizeToFit];
infoScroll.contentSize = CGSizeMake(infoScroll.contentSize.width, infoLabel.frame.size.height);
[infoScroll addSubview:infoLabel];

[self.view addSubview:infoScroll];

}

请提供建议,先行致谢。

你有什么问题? - Jesse Rusak
如所述,我希望ScrollView适应屏幕的大小。我无法弄清如何实现。 - A3O
你可能想要研究一下自动调整大小掩码。 - Jesse Rusak
1个回答

4

通过以下方式修改您的函数:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    // Create a ScrollView and a label
    UIScrollView *infoScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(20.0f, 55.0f, self.view.frame.size.width - 20.0, self.view.frame.size.height - 55)];
    infoScroll.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    UILabel *infoLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    infoLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;        

NSString *labelText = NSLocalizedString (@"InfoText",@"");
    [infoLabel setText:labelText];

    // Tell the label to use an unlimited number of lines
    [infoLabel setNumberOfLines:0];
    [infoLabel setBackgroundColor:[UIColor clearColor]];
    [infoLabel setFont:[UIFont boldSystemFontOfSize:17]];
    infoLabel.textColor = [UIColor colorWithRed:255 green:255 blue:255 alpha:1.0];
    //[infoLabel sizeToFit];

    CGSize infoLabelSize = [infoLabel.text sizeWithFont:infoLabel.font
               constrainedToSize:CGSizeMake(infoScroll.frame.size.width, 5000)
                   lineBreakMode:UILineBreakModeWordWrap];

    infoLabel.frame = CGRectMake(0, 0, infoLabelSize.width, infoLabelSize.height);
    infoScroll.contentSize = infoLabelSize;
    [infoScroll addSubview:infoLabel];

    [self.view addSubview:infoScroll];

}

感谢您的回复和帮助。我做出了更改,但它并没有按照正确的方式工作。在3.5英寸的显示屏上还好,但在4英寸的显示屏上,scrollView太短了。有什么建议吗? - A3O
太好了!这就解决了问题。我只需要在本地化文本中添加几行空白文本,现在它完美地工作了。非常感谢你。我希望我能像你一样获得更多的知识。也许这需要经验积累。我希望如此。非常感谢。 - A3O

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接