问题
I am having trouble dynamically adding a multiline UILabel. Here is the result I'm getting:

I would like the label in the "Summary" box to wrap naturally. Here is the code I'm using to add the label:
-(void)setSummary{
summaryContentLabel = [[UILabel alloc] init];
summaryContentLabel.numberOfLines=0;
summaryContentLabel.lineBreakMode=NSLineBreakByWordWrapping;
summaryContentLabel.text=self.summary;
summaryContentLabel.font=[UIFont fontWithName:@"Helvetica" size:13.0];
[summaryView addSubview:summaryContentLabel];
[summaryContentLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
NSDictionary *views = NSDictionaryOfVariableBindings(summaryView,summaryContentLabel ,summaryLabel);
[summaryView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[summaryLabel]-5-[summaryContentLabel(==100)]-5-|" options:nil metrics:nil views:views]];
}
You'll notice the title of the book wraps the way I want with no problem. That was done in IB. Unfortunately, I have to add this label in code. Auto Layout is also a requirement.
回答1:
Figured it out. I needed to add an additional constraint for the width of the label, like this:
[summaryView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[summaryContentLabel]-|" options:nil metrics:nil views:views]];
回答2:
May be I am late but any way I've found solution. You need to explicitly set preferredMaxLayoutWidth for summaryContentLabel. For example:
summaryContentLabel.preferredMaxLayoutWidth = 200;
And I've noticed that if you do the same view layout via xib then interface builder will set preferredMaxLayoutWidth with correct value.
回答3:
Use this code for multiline label:-
-(void)setSummary {
summaryContentLabel = [[UILabel alloc] init];
summaryContentLabel.numberOfLines=0;
summaryContentLabel.textAlignment = UITextAlignmentLeft;
summaryContentLabel.font=[UIFont fontWithName:@"Helvetica" size:13.0];
[summaryView addSubview:summaryContentLabel];
CGSize size = [self.summary sizeWithFont:[UIFont fontWithName:@"Helvetica" size:13.0] constrainedToSize:CGSizeMake(240, 99999) lineBreakMode:UILineBreakModeWordWrap];
summaryContentLabel.frame=CGRectMake(72, 22, 240, size.height); //set the frame according to your need
summaryContentLabel.text=self.summary;
}
回答4:
It doesn't appear that you're actually setting a frame size to your UILabel. You could always do:
CGRectMake(10, 10, 280, 9999);
For the height and then to make sure it fits properly instead of being a height of 9999 set:
[summaryContentLabel sizeToFit];
来源:https://stackoverflow.com/questions/12901599/ios-dynamically-adding-a-multiline-uilabel