0

I have UILabel in my View that should resize itself based on the content, but it doesn't do so. I have multiline content in it. I tried [label sizeToFit] + label.numberOfLines= 0.

I don't have constraints for the UILabel.

I also tried to use UITextView instead, but there the font just stays on 13 and not as I want on 17. Can you help me?

This is the code that works now:

UILabel *textLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(20, 158, self.view.bounds.size.width-40, 550)];
textLabel2.text = textString;
textLabel2.font = [UIFont fontWithName:@"Helvetica Neue" size:17];
textLabel2.numberOfLines = 0;
[textLabel2 sizeToFit];
[self.scroller addSubview:textLabel2];
4

1 回答 1

1

If you are creating your UILabel programmatically:

This code first sets the UIlabel's text then get the width of the text

UILabel *label = [[UILabel alloc] init];
//set label backgroundColor so you can see the label width changes according to text
[label setBackgroundColor:[UIColor redColor]];
//edit you label text
[label setText:@"very longgggg text"];

//get width of you text and set you font size to 17.0
CGFloat width =  [label.text sizeWithFont:[UIFont systemFontOfSize:17.0f]].width;

//set you label frame
label.frame = CGRectMake(10, 200, width, 30);

//add label to you view
[self.view addSubview:label];

If you're not creating you UILabel programmatically remove the alloc init line and connect you outlets to you xib or storyboard.

于 2014-08-22T14:00:55.080 回答