[英]How to wrap text around attachments using iOS7 Text Kit?
我正在使用新的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];
這工作正常,我可以看到我的圖像在輸出中呈現。 但是,我找不到任何方法來指定圖像對齊方式,或者在圖像周圍包裝文本。
有任何想法嗎?
注意:文本附件與排除路徑不同 - 文本附件是“模型”的一部分,即它是布局管理器執行文本布局的屬性文本字符串的一部分。 而排除路徑是視圖的一部分。
NSTextAttachments
被視為由單個字符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
附加到現有的屬性字符串,並可能在其后附加另一個。 一個怪癖是因為附件是一個角色,所以它不被視為自己的段落。 為了實現這種情況,您需要使用\\n
(換行符)將其包圍。 只需將這些附加到附件的屬性字符串的兩側即可。
希望有所幫助,我花了很長時間才弄明白。
嘗試將bounds
屬性設置為圖像大小。
定義文本坐標系中接收器圖形表示的布局邊界。
所以它應該是:
ta.bounds = (CGRect) { 0, 0, ta.image.size };
ta.bounds = (CGRect) { 0, yPadding, ta.image.size };
改變你需要的yPadding。
當圖像的高度大於行高時,它可以是負數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.