是否存在将归因字符串与本地化结合使用的方法?

时间:2014-03-13 18:34:17

标签: ios nsattributedstring

假设有一个英文字符串,并且要求对文本字符串的特定部分加粗或颜色等:

“word1 word2 WORD3 word4”

这可以通过设置适当范围的属性来实现。

范围可以硬编码为(13,5),但当然不会是可本地化的。

因此,可以通过知道它的第三个单词必须使用粗体来动态确定范围。

但这也不是本地化的。假设一旦该句子被翻译成语言N,它只包含2个单词,或者包含5个单词的语言M?

所以我的问题是如何在没有大量硬编码的情况下将属性字符串与本地化结合使用?

4 个答案:

答案 0 :(得分:10)

我在最新项目中使用的方法是在Localizable.strings文件中使用HTML,然后使用类似的内容生成NSAttributedString

NSString *htmlString = NSLocalizedString(key, comment);

[[NSAttributedString alloc] initWithData:
    [htmlString dataUsingEncoding:NSUTF8StringEncoding]
                         options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                   NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
              documentAttributes:nil
                           error:nil]]

(作为个人喜好,我把这一切都包装成#define LocalizedHTMLForKey(key),所以希望我没有在这个答案中添加任何拼写错误,让它变得清晰......)

答案 1 :(得分:5)

您可以使用某种表示法来表示哪些单词应该加粗,然后使用变换器找到粗体范围并添加适当的属性。

word •word• word word

מילה מילה •מילה• מילה מילה

在这两个句子中,我使用字符来表示中间的单词应该是粗体。然后,我可以使用rangeOfString:options:range:迭代并查找所有范围以粗体并相应地插入属性。

答案 2 :(得分:3)

从Bens的回答中,我创建了一个扩展来帮助我在Swift中做到这一点。

extension NSAttributedString {

    convenience init?(withLocalizedHTMLString: String) {

        guard let stringData = withLocalizedHTMLString.data(using: String.Encoding.utf8) else {
            return nil
        }

        let options: [String : Any] = [
            NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType as AnyObject,
            NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue
        ]

        try? self.init(data: stringData, options: options, documentAttributes: nil)
    }
}

将此初始化程序与HTML标记字符串一起使用,例如:

NSAttributedString(withLocalizedHTMLString: NSLocalizedString("By signing up, you agree to our <u><b>Terms & Privacy Policy</b></u>", comment: "terms and conditions"))

它应该为你完成所有的工作!

答案 3 :(得分:1)

哈里对Swift 4的回答

extension NSAttributedString {

    convenience init?(withLocalizedHTMLString: String) {

        guard let stringData = withLocalizedHTMLString.data(using: String.Encoding.utf8) else {
            return nil
        }

        let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
            NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html as Any,
            NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue
        ]

        try? self.init(data: stringData, options: options, documentAttributes: nil)
    }
}