Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position of NSTextAttachment inside UILabel?

I have a UILabel displaying an NSAttributedString. The string contains text and a UIImage as a NSTextAttachment.

When rendered, is there a way to get the position of the NSTextAttachment in the UILabel?

Edit

Here is the end result I am trying to achieve.

When the text is only 1 line long, the image should be right at the edge of the UILabel. Simple:

Single line UILabel

The problem arises when you have multiple lines, but still want the image to be at the end of the last line:

Multiline UILabel

like image 334
rdougan Avatar asked Jun 02 '14 16:06

rdougan


People also ask

What is Nstextattachment?

The values for the attachment characteristics of attributed strings and related objects.


1 Answers

I can think of one solution (which is more a workaround) and it is applicable only in limited cases. Assuming your NSAttributedString contains text on the left side and image on the right side, you can calculate the size of the text and get the position of the NSTextAttachment with sizeWithAttributes:. This is not a complete solution, as only the x coordinate (i.e. the width of the text part) can be used.

NSString *string = @"My Text String";
UIFont *font = [UIFont fontWithName:@"HelveticaNeue-Italic" size:24.0];
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
CGSize size = [string sizeWithAttributes:attributes];
NSLog(@"%f", size.width); // this should be the x coordinate at which your NSTextAttachment starts

Hope this provides you with some hint.

EDIT:

If you have lines wrapping you can try the following code (string is the string you are putting in the UILabel and self.testLabel is the UILabel):

CGFloat totalWidth = 0;
NSArray *wordArray = [string componentsSeparatedByString:@" "];

for (NSString *i in wordArray) {
    UIFont *font = [UIFont fontWithName:@"HelveticaNeue-Italic" size:10.0];
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
    // get the size of the string, appending space to it
    CGSize stringSize = [[i stringByAppendingString:@" "] sizeWithAttributes:attributes];
    totalWidth += stringSize.width;

    // get the size of a space character
    CGSize spaceSize = [@" " sizeWithAttributes:attributes];

    // if this "if" is true, then we will have a line wrap
    if ((totalWidth - spaceSize.width) > self.testLabel.frame.size.width) {
        // and our width will be only the size of the strings which will be on the new line minus single space
        totalWidth = stringSize.width - spaceSize.width;
    }
}

// this prevents a bug where the end of the text reaches the end of the UILabel
if (textAttachment.image.size.width > self.testLabel.frame.size.width - totalWidth) {
    totalWidth = 0;
}

NSLog(@"%f", totalWidth);
like image 166
VolenD Avatar answered Sep 29 '22 21:09

VolenD