UILabel 有最大高度吗? [英] does UILabel have a maximum height?

查看:19
本文介绍了UILabel 有最大高度吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

没有太多代码要分享,只是一个问题.如果我的标签高度超过 8191 像素,为什么我的标签不可见?

Not too much code to share, just a question. Why is my label invisible if its height is over 8191 pixels?

您可能认为这太过分了,为什么我想要这么长的标签......它是动态的,所以你永远不知道.

You might think this is way too much and why in the world do i want such a long label... it's dynamic, so you never know.

事情是这样的:我创建了我的 UIScrollView 并开始在 init 中添加标签,其中 5 个.我设置了文本,一切顺利.我有一个方法可以获取 5 个标签,使用 NSString sizeWithFont:constrainedToSize:lineBreakMode: 获取大小,重新排列它们并重置 UIScrollView 的 contentHeight.都好.事实是,当标签的高度正好超过 8191 像素(宽度超过 300)时,它就会消失,不可见,噗!走了.

So this is how it goes: I create my UIScrollView and start adding labels in init, 5 of them. I set the text and good to go. I have a method that will take the 5 labels, get the size with the NSString sizeWithFont:constrainedToSize:lineBreakMode:, rearrange them and reset the contentHeight of the UIScrollView. All good. Thing is, when a label is exactly over 8191 in height pixels (and 300 in width), it disappears, not visible, puff! gone.

如果我不能让它工作,我想我可以将文本分成多个部分并创建额外的 UILabels,但我想避免这种情况.

If I can't get this to work, I guess I can split the text in multiple pieces and create extra UILabels, but I want to avoid that.

有什么想法吗?

这是一些虚拟代码,易于理解

Here is some dummy code, easy to follow

NSError *er = nil;
    // this file can be found here: 
    // https://gist.github.com/3167635
NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"lorem.txt"];
NSString *labelText = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&er];
if(er != nil)
    NSLog(@"Error: %@", er);

UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame: self.view.bounds];
[scrollView setBackgroundColor:[UIColor whiteColor]];

UILabel *label = [[UILabel alloc] init];
[label setBackgroundColor:[UIColor whiteColor]];
[label setNumberOfLines:0];
[label setText:labelText];


CGSize size = [labelText sizeWithFont:label.font constrainedToSize:CGSizeMake(300, CGFLOAT_MAX) lineBreakMode:UILineBreakModeCharacterWrap];

NSLog(@"Size: %@", NSStringFromCGSize(size));
CGRect labelFrame;
labelFrame.origin = CGPointMake(10, 0);
labelFrame.size = size;

[label setFrame:labelFrame];
[scrollView setContentSize:size];   
[scrollView addSubview:label];

[[self view] addSubview:scrollView];

虚拟文本很大,使标签不可见.

The dummy text is huge, makes the label not visible.

推荐答案

我建议使用 sizeToFit 属性而不是自己设置高度由于此属性将根据您的文本设置标签的高度,因此您不必费力设置高度

I'm suggesting using sizeToFit property instead of setting the height yourself as this property will set the height of the label according to ur text u don't have to take the effort of setting the height

或者你可以用这一行来代替

or you can use this line instead

CGSize maximumLabelSize = CGSizeMake(headerView.frame.size.height,over 8191 );

这篇关于UILabel 有最大高度吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆