0

In my project I want to add an attributed text in UILabel placed on the xib. It's working perfectly, but if large text appears it shows some issues.

My current implementation:

- (void)viewDidLoad
{
    [super viewDidLoad];
    _demoLabel.numberOfLines = 0;
    _demoLabel.lineBreakMode = NSLineBreakByWordWrapping;
    _demoLabel.attributedText = [self demoNameWithFontSize:21 andColor:[UIColor redColor]];

}

- (NSMutableAttributedString *)demoNameWithFontSize:(CGFloat)fontSize andColor:(UIColor *)color
{
    NSMutableAttributedString *attributedText = nil;
    NSString *demoName = @"Blah blah blah";
    UIFont  *demoFont  = [UIFont fontWithName:@"Zapfino" size:fontSize];
    attributedText = [[NSMutableAttributedString alloc] initWithString:demoName];
    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    paragraph.lineBreakMode = NSLineBreakByWordWrapping;
    [attributedText addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, [demoName length])];
    [attributedText addAttribute:NSFontAttributeName value:demoFont range:NSMakeRange(0, [demoName length])];
    [attributedText addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, [demoName length])];

    return attributedText;
}

Output:

Zapfino

Issue:

It is not displaying the whole text, even if I applied the NSMutableParagraphStyle. How can I solve this ?

Alternative I found:

If I change

UIFont  *demoFont  = [UIFont fontWithName:@"Zapfino" size:fontSize];

to

UIFont  *demoFont  = [UIFont systemFontOfSize:fontSize];

It'll work and gives output like:

System

But the issue is I need to use custom font, can't use default font. Also cannot change the font size.

I checked UILabel class reference and googled, but couldn't find a solution. Please help me. Is there anyway to span this text into multiple lines ?

Midhun MP
  • 103,496
  • 31
  • 153
  • 200

1 Answers1

0

You need to resize the UILabel to fit the text.

You can calculate the size with the boundingRectWithSize:options:context: NSAttributedString class method, which takes an attributed string and calculates the size within a set rect based on all the attributes of the string.

runmad
  • 14,846
  • 9
  • 99
  • 140