18

新しい Text Kit API を使用して、属性付きテキストに添付ファイルを追加しています。

// create an attachment for each image
NSTextAttachment* ta = [NSTextAttachment new];
ta.image = [UIImage imageNamed:@"imageName"];

// add to the attributed text string
NSAttributedString* rep = [NSAttributedString attributedStringWithAttachment:ta];
[myAttributedTextString appendAttributedString:rep];

これは正常に機能し、出力でレンダリングされた画像を見ることができます。ただし、画像の配置を指定したり、画像をテキストで囲んだりする方法が見つかりません。

何か案は?

注:テキスト添付は除外パスとは異なります。テキスト添付は「モデル」の一部です。つまり、レイアウト マネージャーがテキスト レイアウトを実行する属性付きテキスト文字列の一部です。一方、除外パスはビューの一部です。

4

3 に答える 3

20

NSTextAttachmentsでは 1 文字として扱われNSAttributedStringます。そのため、配置を調整するには、テキストの場合と同様に行う必要があります。attachment.bounds最終的にこれを理解するのに、何時間もいじりました(適切に動作することはありませんでした)。を水平方向に整列する方法の例を次に示しますNSTextAttachment

#def BETWEEN_SECTION_SPACING 10  

// creates a text attachment with an image

NSTextAttachment *attachment = [[NSTextAttachment alloc] init];

attachment.image = [UIImage imageNamed:@"sample_image.jpg"];

NSMutableAttributedString *imageAttrString = [[NSAttributedString attributedStringWithAttachment:attachment] mutableCopy];



// sets the paragraph styling of the text attachment

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init] ;

[paragraphStyle setAlignment:NSTextAlignmentCenter];            // centers image horizontally

[paragraphStyle setParagraphSpacing:BETWEEN_SECTION_SPACING];   // adds some padding between the image and the following section

[imageAttrString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [imageAttrString length])];

この後imageAttrString、既存の属性付き文字列に追加し、おそらくその後に別の文字列を追加します。1 つの癖は、添付ファイルが文字であるため、それ自体の段落として扱われないことです。\nそのためには、 (改行文字)で囲む必要があります。これらを添付ファイルの属性付き文字列の両側に追加するだけです。

それが役立つことを願っています。理解するのに何年もかかりました。

于 2013-11-05T12:08:30.730 に答える
1
ta.bounds = (CGRect) { 0, yPadding, ta.image.size }; 

必要な yPadding を変更します。
画像の高さが行の高さよりも大きい場合、負になることがあります。

于 2014-12-01T06:06:31.673 に答える