- (void)viewDidLoad{[super viewDidLoad];
// 20 point top and left margin. Sized to leave 20 pt at right.CGRect labelFrame = CGRectMake(20, 20, 280, 150);UILabel *myLabel = [[UILabel alloc] initWithFrame:labelFrame];[myLabel setBackgroundColor:[UIColor orangeColor]];
NSString *labelText = @"I am the very model of a modern Major-General, I've information vegetable, animal, and mineral";[myLabel setText:labelText];
// Tell the label to use an unlimited number of lines[myLabel setNumberOfLines:0];[myLabel sizeToFit];
[self.view addSubview:myLabel];}
Call sizeToFit to reduce the frame size so the contents just fit:
[myLabel sizeToFit]
The labels frame is now just high and wide enough to fit your text. The top left should be unchanged. I have tested this only with the top left-aligned text. For other alignments, you might have to modify the frame afterward.
// adjust the height of a multi-line label to make it align vertical with top+ (void) alignLabelWithTop:(UILabel *)label {CGSize maxSize = CGSizeMake(label.frame.size.width, 999);label.adjustsFontSizeToFitWidth = NO;
// get actual heightCGSize actualSize = [label.text sizeWithFont:label.font constrainedToSize:maxSize lineBreakMode:label.lineBreakMode];CGRect rect = label.frame;rect.size.height = actualSize.height;label.frame = rect;}
[labelName setText:@"This is just a demo"];
NSMutableString *yourString1= @"This is just a demo";
// breaking stringlabelName.lineBreakMode=UILineBreakModeTailTruncation;labelName.numberOfLines = 3;
CGSize maximumLabelSize1 = CGSizeMake(276,37); // Your Maximum text size
CGSize expectedLabelSize1 = [yourString1 sizeWithFont:labelName.fontconstrainedToSize:maximumLabelSize1lineBreakMode:labelName.lineBreakMode];
[labelName setText:yourString1];
CGRect newFrame1 = labelName.frame;if (expectedLabelSize1.height>=10){newFrame1.size.height = expectedLabelSize1.height;}
labelName.frame = newFrame1;
func viewDidLoad() {
super.viewDidLoad()
// 20 point top and left margin. Sized to leave 20 pt at right.let labelFrame = CGRect(x: 20, y: 20, width: 280, height: 150)let myLabel = UILabel(frame: labelFrame)myLabel.backgroundColor = UIColor.orange
let labelText = "I am the very model of a modern Major-General,I've information vegetable, animal, and mineral"myLabel.text = labelText
// Tell the label to use an unlimited number of linesmyLabel.numberOfLines = 0myLabel.sizeToFit()
view.addSubview(myLabel) // add label}