Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit NSAttributedString number of lines

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?

like image 374
ItayAmza Avatar asked Feb 10 '15 17:02

ItayAmza


1 Answers

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.

like image 192
Bruno Muniz Avatar answered Nov 13 '22 23:11

Bruno Muniz