ken
ken

Reputation: 31

How to get length of text for last line in UITextView

In my app, I'm trying to have the UILable time text aligned in a way like WhatsApp where if the last sentence of a UITextView's message text is too long the time would be pushed to the next line. So I'm actually trying to align the UILabel's time according to the UITextView's message box.

message box time layout image

This is a text message.  7:16PM


This is a longer
text message.    7:15PM


This is an even longer
text message till end.
                7.15PM

One way I could think of was to use UITextView's class and grab the length of the last line and calculate the text width as compared with the UITextView's width to know if it exceeds but no luck. Is there any way?

Upvotes: 2

Views: 1104

Answers (2)

ken
ken

Reputation: 31

This is the code that I wrote which solved my issue. Thanks to Greg for pointing me in the right direction.

+ (BOOL)didTextMoveToNewline:(NSString *)text previousSize:(CGSize)previousSize {
    UIFont *messageBubbleFont = [UIFont systemFontOfSize:14.0f];
    float maximumTextWidth = 188;

    NSString *finalText = [[NSString alloc] init];
    finalText = [NSString stringWithFormat:@"%@ 10:00PM ", text];
    CGRect stringRect = [finalText boundingRectWithSize:CGSizeMake(maximumTextWidth, CGFLOAT_MAX)
                                           options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
                                        attributes:@{ NSFontAttributeName : messageBubbleFont }
                                           context:nil];

    CGSize stringSize = CGRectIntegral(stringRect).size;

    if (stringSize.height > previousSize.height)
        return YES;
    else
        return NO;
}

Upvotes: 1

D. Greg
D. Greg

Reputation: 1000

The hack would be to automatically add a blank space the length of the time to the end of every message.

let userMessageLabel.text = userMessage + "        "

Then let the time always overlap the last line. If the amount of spaces is correct, the text and time will never touch.

Upvotes: 0

Related Questions