Summary of common Settings for UILabel text display in iOS applications

  • 2020-06-15 10:18:03
  • OfStack

Create the UIlabel object


UILabel* label = [[UILabel alloc] initWithFrame:self.view.bounds];

Set display text

label.text = @"This is a UILabel Demo,";

Set the text font

label.font = [UIFont fontWithName:@"Arial" size:35];

Set the text color

label.textColor = [UIColor yellowColor];

Sets the horizontal display position of the text

label.textAlignment = UITextAlignmentCenter;

Set the background color

label.backgroundColor = [UIColor blueColor];

Sets the way words are folded

label.lineBreakMode = UILineBreakModeWordWrap;

Sets whether label can display multiple rows and 0 can display multiple rows

label.numberOfLines = 0;

Adjust the UILabel height dynamically

[label sizeToFit];

The height of UILabel is dynamically set based on the content size

CGSize size = [label.text sizeWithFont:label.font constrainedToSize:self.view.bounds.size lineBreakMode:label.lineBreakMode]; CGRect rect = label.frame; rect.size.height = size.height; label.frame = rect; 

Newline mode

label.text = @"This is a UILabel Demo,";
0
Other:
UILineBreakModeWordWrap = 0,
Lines are wrapped in words and truncated in units.
UILineBreakModeCharacterWrap,
Line wrapping in character, truncated in character.
UILineBreakModeClip,
Wrap lines in words. Truncation in characters.
UILineBreakModeHeadTruncation,
Wrap lines in words. If it is a single line, there is an ellipsis at the beginning. If it is multiple lines, there is an ellipsis in the middle, followed by four characters.
UILineBreakModeTailTruncation,
Wrap lines in words. Both single and multiple lines have an ellipsis at the end.
UILineBreakModeMiddleTruncation,
Wrap lines in words. Both single and multiple lines have an ellipsis in the middle, followed by only two characters.

Tip: Automatically ADAPTS the width and height according to the length of the string


// this frame I'm going to reset it, so that's fine, but I'm going to reset it later size .
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,0,0)];
    label.numberOfLines = 0;
    label.backgroundColor = [UIColor clearColor];
   
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:20],};
   
    NSString *str = @"abcdefg You took your class and you got yours ";
    CGSize textSize = [str boundingRectWithSize:CGSizeMake(100, 100) options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;;
   
    [label setFrame:CGRectMake(100, 100, textSize.width, textSize.height)];
    label.textColor = [UIColor greenColor];
    label.text = str;
    [self.view addSubview:label];


Related articles: