ios - 用 NSTextAttachment 替换出现的 NSString
<p><p>我有一个 UITextView,我想使用 <code>NSTextAttachment</code> 将一些字符串替换为特定图像。我能够将图像附件插入到 <code>UITextView</code> 并且我有一个方法,该方法从 TextView 的属性文本中返回一个 <code>NSString</code> 用特定 <code> 替换附件NSString</code>:</p>
<pre><code>-(NSString*)getStringFromAttributedString{
__block NSString *str = self.attributedText.string; // Trivial String representation
__block NSMutableString *string = ; // To store customized text
[self.attributedText enumerateAttributesInRange:NSMakeRange(0, self.attributedText.length) options:0 usingBlock:^(NSDictionary *attributes, NSRange range, BOOL *stop){
// enumerate through the attributes
NSString *v;
NSObject *x = ;
if(x){ // YES= This is an attachment
v = ;
if(v == nil){
v=@"";
}
}else{
v = ; // NO=This is a text block.
}
// append value to string
;
}];
return string;
}
</code></pre>
<p>现在我需要一个从 <code>NSString</code> 返回 <code>NSAttributedString</code> 的方法,用图像附件替换一些出现的字符串,类似这样,但我无法做到工作。</p>
<pre><code>-(NSMutableAttributedString*)getAttributedStringFromString:(NSString*)string{
// create NSMutableAttributedString from NSString in input
NSMutableAttributedString *attrString = [ initWithString:string];
// create the attachment with image
NSTextAttachment *textAttachment = [ init];
textAttachment.image = ;
textAttachment.bounds = (CGRect) {0, -2, textAttachment.image.size};
// create NSMutableAttributedString with image attachment
NSMutableAttributedString *attrStringWithImage = [ mutableCopy];
// here I'd like to replace all occurrences of a string (":D" this string for example) with my NSMutableAttributedString with image attachment).
return string;
}
</code></pre>
<p>我该怎么办?</p>
<p>谢谢,希望我自己解释一下。</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>这是我的工作解决方案:</p>
<pre><code>-(NSMutableAttributedString*)getEmoticonStringFromString:(NSString*)string{
NSMutableAttributedString *final = ; //To store customized text
NSInteger len = ;
unichar buffer;
;
for(int i = 1; i < len; i++) {
if(buffer == ':' && buffer == 'D'){
NSMutableAttributedString *attrString = [ initWithString:string];
NSTextAttachment *textAttachment = [ init];
textAttachment.image = toSize:CGSizeMake(18.0f, 18.0f)];
textAttachment.bounds = (CGRect) {0, -2, textAttachment.image.size};
NSMutableAttributedString *attrStringWithImage = [ mutableCopy];
NSMutableParagraphStyle *paragraphStyle = [ init] ;
;
;
)];
;
i++;
}else{
initWithString:]] atIndex:final.length];
if(i == len-1){
initWithString:]] atIndex:final.length];
}
}
}
return final;
</code></pre>
<p>}</p></p>
<p style="font-size: 20px;">关于ios - 用 NSTextAttachment 替换出现的 NSString,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/27617846/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/27617846/
</a>
</p>
页:
[1]