9

我有一个UILabel显示NSAttributedString. 该字符串包含 text 和 aUIImage作为NSTextAttachment.

渲染时,有没有办法获取 中的NSTextAttachment位置UILabel

编辑

这是我想要达到的最终结果。

当文本只有 1 行长时,图像应该正好在UILabel. 简单的:

单行UILabel

当您有多行但仍希望图像位于最后一行的末尾时,就会出现问题:

多行UILabel

4

1 回答 1

4

我可以想到一种解决方案(这更像是一种解决方法),它仅适用于有限的情况。假设您NSAttributedString包含左侧的文本和右侧的图像,您可以计算文本的大小并NSTextAttachment使用sizeWithAttributes:获取位置。这不是一个完整的解决方案,因为只能使用x坐标(即width文本部分的坐标)。

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

希望这能给你一些提示。

编辑:

如果您有换行,您可以尝试以下代码(string是您放入 UILabel 的字符串,并且self.testLabel是 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);
于 2014-06-10T08:24:26.533 回答