如何在swift中格式化属性字符串?

时间:2017-09-26 18:29:46

标签: ios iphone swift string nsattributedstring

我正在处理通知页面,其中输入主要来自JSON文件,我需要将它们与本地化字符串结合起来。这应该是它的样子:

Sketch design

可以预测,彩色部分来自JSON文件,其余部分来自Localizable.strings。这是来自Localizable文件:

"%@ has joined %@"

如果我使用String(format: String, [...])我有一个纯黑色文字,我无法指定需要着色的部分。

NSAttributedString我需要相同的功能,但它没有这种方法。

那么如何格式化属性字符串呢?

3 个答案:

答案 0 :(得分:0)

检查以下示例:

var myMutableString = NSMutableAttributedString()

myMutableString = NSMutableAttributedString(string: "Your full label textString")

myMutableString.setAttributes([NSFontAttributeName : UIFont(name: "HelveticaNeue-Light", size: CGFloat(17.0))!
        , NSForegroundColorAttributeName : UIColor(red: 232 / 255.0, green: 117 / 255.0, blue: 40 / 255.0, alpha: 1.0)], range: NSRange(location:12,length:8)) // What ever range you want to give

yourLabel.attributedText = myMutableString

或其他方式:

要更改文本长度的颜色,您需要知道字符串中有颜色字符的开始和结束索引,例如

var main_string = "Hello World"
var string_to_color = "World"

var range = (main_string as NSString).rangeOfString(string_to_color)

然后转换为属性字符串,并使用NSForegroundColorAttributeName添加'添加属性':

var attributedString = NSMutableAttributedString(string:main_string)
attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor() , range: range)

答案 1 :(得分:0)

尝试以下代码并相应地更新您的逻辑。

    let localizableStr = "%@ has joined %@"
    let localisedStr = NSLocalizedString(localizableStr, comment: "")

    let components = localizableStr.components(separatedBy: "%@")

    let formatterStr = components.count > 2 ? components[1] : "has joined"

    let evaluatedStr = NSString(format: localisedStr as NSString, "Rishi ", "Stack OVerflow")

    let attributedStr = NSMutableAttributedString(string: evaluatedStr as String)
    attributedStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.brown, range: NSMakeRange(0, attributedStr.length))

    let formatterStrRange = evaluatedStr.range(of: formatterStr, options: .caseInsensitive)
    attributedStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.black, range: formatterStrRange)

答案 2 :(得分:0)

我的两个本地化字符串:

"welcome message" = "%@ has joined %@";
"welcome message" = "انضم %@ إلى %@";

结果
enter image description here

enter image description here


extension String {

 func localisedAttributedString(_ replacements: CVarArg..., attributes: [NSAttributedString.Key : Any], replacementAttributes: [[NSAttributedString.Key : Any]?] ) -> NSAttributedString {
        

        let message = String.init(format: NSLocalizedString(self, comment: ""), arguments: replacements)
        
        let attributedString =  NSMutableAttributedString(string: message, attributes: attributes)
       
        
        for (i, replacement) in replacements.enumerated() {
            
            if let att = replacementAttributes[i] {
                
                let range = (attributedString.string.range(of: "\(replacement)".localized)?.nsRange(in: attributedString.string)) ?? NSRange(location: 0, length: 0)
                attributedString.addAttributes(att as [NSAttributedString.Key : Any], range: range)
            }
            
        }
        
        return attributedString
    }

}

如何使用

//General attr: Applied to the entire string
let generalAttributes = [NSAttributedString.Key.font:  UIFont.getFont(.regular, size: 20)]


//Additional attrs applied to the replacement / dynamic bits. You can pass nil too
let nameAttributes = [ NSAttributedString.Key.backgroundColor: UIColor.red]
let companyAttributes = [ NSAttributedString.Key.foregroundColor: UIColor.blue]
        
myLabel.attributedText = "welcome message".localisedAttributedString("adam".localized, "space".localized, attributes: generalAttributes, replacementAttributes: [nameAttributes, companyAttributes] )