【问题标题】:change string with picture in swift用图片快速更改字符串
【发布时间】:2018-07-25 09:48:39
【问题描述】:

我在UILabel 中有一个字符串,该字符串包含一个或多个表情符号,但只有“:cool:”或“:crazy:”之类的名称。

如何将字符串中的单词替换为 .png ?

func checkString(pString: String) -> String {

    var replaced = pString //get the String
    var found = ""
    var image = UIImage() //Emoji

    for i in 1...bib.count { //bib = array(Int:String) with all names of the Emoji
        if pString.range(of: bib[i]!) != nil {
            found = bib[I]!

            //picBib is a array(String:String) with the Emoji name and the path

            if let picURL: String = picBib[found] as? String {
                image = UIImage(named: picURL)!
            }
            //cute the ":cool:" out of the String
            replaced = pString.replacingOccurrences(of: found, with: "")
            let imageView = UIImageView(image: image)
            imageView.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
        }
    }
    return replaced
}

我认为这样的事情有更好的方法.. 表情符号不在图书馆里。我把它们放在 JSON {";P":";P.png",":)":"colon_).png" ...

也许我必须从 UILabel 切换到 ..?

【问题讨论】:

  • 使用NS(Mutable)AttributedStringNSTextAttachment。找出所有出现的:cool:(和其他),并将它们替换为您对应的图像。

标签: swift string uilabel nsattributedstring emoji


【解决方案1】:

未经测试,但应该可以解决问题:

let string = "Hello :cool:, no? What a :crazy: day!"
let emojiDict: [String: String] = [":cool:": "cool.png", ":crazy:": "crazy.png"]

let attributedString = NSMutableAttributedString(string: string)

for (anEmojiTag, anEmojiImageName) in emojiDict {
    let pattern = NSRegularExpression.escapedPattern(for: anEmojiTag)
    let regex = try? NSRegularExpression(pattern: pattern,
                                         options: [])
    if let matches = regex?.matches(in: attributedString.string,
                                    options: [],
                                    range: NSRange(location: 0, length: attributedString.string.utf16.count)) {
        for aMatch in matches.reversed() {
            let attachment = NSTextAttachment()
            attachment.image = UIImage(named: anEmojiImageName)
            //attachment.bounds = something //if you need to resize your images
            let replacement = NSAttributedString(attachment: attachment)
            attributedString.replaceCharacters(in: aMatch.range, with: replacement)
        }
    }
}

myLabel.attributedText = attributedString

什么想法:
使用NS(Mutable)AttributedString 可以将图像放入文本
使用NSRegularExpression 查找所有匹配项
从末尾开始替换值(否则,找到的所有范围都可能会被破坏,因为出现的长度和替换的长度不会相同。

编辑: 用 Objective-C 快速编写(未选中)

NSString *string = @"Hello :cool:, no? What a :crazy: day!";
NSDictionary *emojiDict = @{@":cool:": @"cool.png", @":crazy:": @"crazy.png"};

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

for (NSString *anEmojiText in emojiDict)
{
    NSString *anEmojiImageName = emojiDict[anEmojiText];
    NSString *pattern = [NSRegularExpression escapedPatternForString:anEmojiText];
    NSError *regexError = nil;
    NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:&regexError];
    if (regexError) { /* Error management missing here */ }
    NSArray *matches = [regex matchesInString:[attributedString string] options:0 range:NSMakeRange(0, [attributedString length])];

    [matches enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(NSTextCheckingResult * _Nonnull aResult, NSUInteger idx, BOOL * _Nonnull stop) {
        NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
        [attachment setImage:[UIImage imageNamed:anEmojiImageName]];
        //[attachment setBounds:something]; //if you need to resize your images
        NSAttributedString *replacement = [NSAttributedString attributedStringWithAttachment:attachment];
        [attributedString replaceCharactersInRange:[aResult range] withAttributedString:replacement];
    }];
}

[myLabel setAttributedText:attributedString];

【讨论】:

  • 谢谢!它有效 wubwub(:我不知道这些事情哇。我还有很长的路要走......
  • 你好,非常感谢你的解决方案,但现在我正在使用网络图像,你能给我一些理想的吗?我使用 kingfisher 加载异步图像,但是当图像加载成功时它不会显示在屏幕上
  • 将 NSTextAttachment 与来自 URL 的图像一起使用是另一种问题。查看那里的逻辑:stackoverflow.com/questions/28257442/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-11
  • 1970-01-01
  • 2011-03-01
  • 2021-04-11
  • 2017-06-12
  • 1970-01-01
相关资源
最近更新 更多