8

is there a way to limit number of lines in paragraph in NSAttributedString?
Im appending two strings in NSAttributedString and i want them to be maximum 3 lines, the first string will be 1-2 lines , truncated if needed. and the second string should be always on the last line
Something like:

this is my first string
if its too long i't will get trun...
But this is my second string

what i did is:

    // First string
    NSAttributedString *first = [[NSAttributedString alloc] initWithString:@"this is my first string if its too long i't will get trunticated"
                                                               attributes:@{NSForegroundColorAttributeName:[UIColor redColor],
                                                                            NSFontAttributeName:[UIFont fontWithName:@"HelveticaNeue-Light" size:17.0]];
    [str appendAttributedString:first];

    // New line
    [str appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n"]];

    // Add photo count
    NSAttributedString *second = [[NSAttributedString alloc] initWithString:@"But this is my second string"
                                                                attributes:@{NSForegroundColorAttributeName:[UIColor redColor],
                                                                             NSFontAttributeName:[UIFont fontWithName:@"HelveticaNeue-Light" size:14.0]}];
    [str appendAttributedString:second];

But the result is:

this is my first string
if its too long i't will get
trunticated

The first string takes the first 3 lines and push the second string out of the label.
How can i limit the first string paragraph to 2 lines?

ItayAmza
  • 819
  • 9
  • 21

2 Answers2

1

You can count the amount of letters that your graphic component (UITextView or UITextField) can handle using uppercase and bigger width ones repeatedly to see this. Than, use:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{}

to check every input, if the amount is enough, or if it stills available for more letters. Create a character limit and decrease it everytime this method is called.

Bruno Muniz
  • 316
  • 3
  • 17
0

Limit the number of lines with one constraint !

Simply add a NSLayoutConstraint on your UILabel with following values :

  • attribute = NSLayoutAttributeHeight ('Height' in Storyboard)
  • relation = NSLayoutRelationLessThanOrEqual ('Less Than or Equal' in Storyboard)
  • constant = height-for-number-of-lines-you-want

See Storyboard integration :

See storyboard integration

Frédéric
  • 726
  • 8
  • 8