9

UILabel表示していNSAttributedStringます。文字列には、テキストと a が含まれていUIImageますNSTextAttachment

レンダリング時に の位置を取得する方法はありNSTextAttachmentますUILabelか?

編集

これが私が達成しようとしている最終結果です。

テキストの長さが 1 行のみの場合、画像は の端に配置する必要がありUILabelます。単純:

単一行 UILabel

複数の行があるが、画像を最後の行の最後に配置したい場合に問題が発生します。

マルチライン UILabel

4

1 に答える 1

4

1 つの解決策 (より回避策) を考えることができますが、それは限られた場合にのみ適用できます。NSAttributedString左側にテキスト、右側に画像が含まれていると仮定すると、テキストのサイズを計算しNSTextAttachmentsizeWithAttributes:での位置を取得できます。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.testLabelUILabel です):

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 に答える