does UILabel have a maximum height?

一个人想着一个人 提交于 2019-12-23 12:56:22

问题


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.

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.

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.

Any ideas?

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.


回答1:


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 );


来源:https://stackoverflow.com/questions/11623317/does-uilabel-have-a-maximum-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!