草庐IT

ios - 将出现的 NSString 替换为 NSTextAttachment

coder 2024-01-24 原文

我有一个 UITextView,我想使用 NSTextAttachment 将一些字符串替换为特定图像。我能够将图像附件插入到 UITextView 并且我有一个方法,从 TextView 的属性文本返回一个 NSString 用特定的 替换附件NSString:

-(NSString*)getStringFromAttributedString{ 
__block NSString *str = self.attributedText.string; // Trivial String representation
__block NSMutableString *string = [NSMutableString new]; // 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 = [attributes valueForKey:@"NSAttachment"];  
    if(x){ // YES= This is an attachment       
        v = [Fuctions getObjectTag:x];     
        if(v == nil){
            v=@"";
        }
    }else{
        v = [str substringWithRange:range]; // NO=This is a text block.
    }  
    // append value to string
    [string appendString:v];
}];
return string;
}

现在我需要一个从 NSString 返回 NSAttributedString 的方法,用图像附件替换一些出现的字符串,类似这样但我做不到工作。

-(NSMutableAttributedString*)getAttributedStringFromString:(NSString*)string{

    // create NSMutableAttributedString from NSString in input
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string]; 
    // create the attachment with image
    NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
    textAttachment.image = [UIImage imageNamed:@"myImageName.png"];
    textAttachment.bounds = (CGRect) {0, -2, textAttachment.image.size};
    // create NSMutableAttributedString with image attachment
    NSMutableAttributedString *attrStringWithImage = [[NSAttributedString attributedStringWithAttachment:textAttachment] 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;
}

我该怎么办?

谢谢,希望我解释清楚了。

最佳答案

这是我的工作解决方案:

-(NSMutableAttributedString*)getEmoticonStringFromString:(NSString*)string{

NSMutableAttributedString *final = [NSMutableAttributedString new]; //To store customized text
NSInteger len = [string length];
unichar buffer[len];
[string getCharacters:buffer range:NSMakeRange(0, len)];

for(int i = 1; i < len; i++) {
    if(buffer[i-1] == ':' && buffer[i] == 'D'){

        NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string];

        NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
        textAttachment.image = [Functions scaleImage:[UIImage imageNamed:@"myImageName"] toSize:CGSizeMake(18.0f, 18.0f)];
        textAttachment.bounds = (CGRect) {0, -2, textAttachment.image.size};

        NSMutableAttributedString *attrStringWithImage = [[NSAttributedString attributedStringWithAttachment:textAttachment] mutableCopy];

        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init] ;
        [paragraphStyle setAlignment:NSTextAlignmentLeft];
        [paragraphStyle setLineSpacing:2.0f];
        [attrString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [attrString length])];

        [final insertAttributedString:attrStringWithImage atIndex:final.length];

        i++;
    }else{

        [final insertAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%c", buffer[i-1]]] atIndex:final.length];
        if(i == len-1){

            [final insertAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%c", buffer[i]]] atIndex:final.length];
        }
    }
}
return final;

关于ios - 将出现的 NSString 替换为 NSTextAttachment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27617846/

有关ios - 将出现的 NSString 替换为 NSTextAttachment的更多相关文章

  1. ruby 正则表达式 - 如何替换字符串中匹配项的第 n 个实例 - 2

    在我的应用程序中,我需要能够找到所有数字子字符串,然后扫描每个子字符串,找到第一个匹配范围(例如5到15之间)的子字符串,并将该实例替换为另一个字符串“X”。我的测试字符串s="1foo100bar10gee1"我的初始模式是1个或多个数字的任何字符串,例如,re=Regexp.new(/\d+/)matches=s.scan(re)给出["1","100","10","1"]如果我想用“X”替换第N个匹配项,并且只替换第N个匹配项,我该怎么做?例如,如果我想替换第三个匹配项“10”(匹配项[2]),我不能只说s[matches[2]]="X"因为它做了两次替换“1fooX0barXg

  2. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  3. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  4. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  5. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  6. ruby - Ruby gsub 替换中的行为不一致? - 2

    两个gsub产生不同的结果。谁能解释一下为什么?代码也可在https://gist.github.com/franklsf95/6c0f8938f28706b5644d获得.ver=9999str="\tCFBundleDevelopmentRegion\n\ten\n\tCFBundleVersion\n\t0.1.190\n\tAppID\n\t000000000000000"putsstr.gsub/(CFBundleVersion\n\t.*\.).*()/,"#{$1}#{ver}#{$2}"puts'--------'putsstr.gsub/(CFBundleVersio

  7. ruby - 使用 rbenv 和 ruby​​-build 构建 ruby​​ 失败,出现 undefined symbol : SSLv2_method - 2

    我正在尝试在配备ARMv7处理器的SynologyDS215j上安装ruby​​2.2.4或2.3.0。我用了optware-ng安装gcc、make、openssl、openssl-dev和zlib。我根据README中的说明安装了rbenv(版本1.0.0-19-g29b4da7)和ruby​​-build插件。.这些是随optware-ng安装的软件包及其版本binutils-2.25.1-1gcc-5.3.0-6gconv-modules-2.21-3glibc-opt-2.21-4libc-dev-2.21-1libgmp-6.0.0a-1libmpc-1.0.2-1libm

  8. ruby-on-rails - 在这种情况下我如何模拟一个对象?没有明显的方法可以用模拟替换对象 - 2

    假设我在Store的模型中有这个非常简单的方法:defgeocode_addressloc=Store.geocode(address)self.lat=loc.latself.lng=loc.lngend如果我想编写一些不受地理编码服务影响的测试脚本,这些脚本可能已关闭、有限制或取决于我的互联网连接,我该如何模拟地理编码服务?如果我可以将地理编码对象传递到该方法中,那将很容易,但我不知道在这种情况下该怎么做。谢谢!特里斯坦 最佳答案 使用内置模拟和stub的rspecs,你可以做这样的事情:setupdo@subject=MyCl

  9. ruby - 如何搜索、递增和替换 Ruby 字符串中的整数子字符串? - 2

    我有很多这样的文档:foo_1foo_2foo_3bar_1foo_4...我想通过获取foo_[X]的所有实例并将它们中的每一个替换为foo_[X+1]来转换它们。在这个例子中:foo_2foo_3foo_4bar_1foo_5...我可以用gsub和一个block来做到这一点吗?如果不是,最干净的方法是什么?我真的在寻找一个优雅的解决方案,因为我总是可以暴力破解它,但我觉得有一些正则表达式技巧值得学习。 最佳答案 我(完全)不懂Ruby,但类似这样的东西应该可以工作:"foo_1foo_2".gsub(/(foo_)(\d+)/

  10. ruby - 改变替换的大小写 - 2

    我有以下内容:text.gsub(/(lower)(upper)/,'\1\2')我可以将\2替换为大写吗?类似于:sed-e's/\(abc\)/\U\1/'这在Ruby中可行吗? 最佳答案 查看gsub文档:str.gsub(模式){|匹配|block}→new_str在block形式中,当前匹配字符串作为参数传入,$1、$2、$`、$&、$'等变量将被适当设置。block返回的值将替换为每次调用的匹配项。"alowerupperb".gsub(/(lower)(upper)/){|s|$1+""+$2.upcase}

随机推荐