在格式化的字符串内,将字符串加粗

时间:2019-04-15 15:00:48

标签: ios swift string

我有一个像这样的字符串:

  

您的分数是%@。

我希望字符串变为:

  

您的分数是完美

我当时想使用:

let attrs = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 15)]
let boldAttributedString = NSMutableAttributedString(string: "perfect".localized(), attributes: attrs)
String(format: "Your string is %@.", boldAttributedString) 

我知道绕过NSMutableString和属性字符串的方式,但是我不确定是否可行,因为我没有办法计算字数,因为在其他语言中,它可能更短或更短order ...“ perfect”的值来自一个枚举值。

关于如何解决此问题的任何想法?

1 个答案:

答案 0 :(得分:0)

您可以使用NSAttributedString 追加 文本和属性:

    let normalAttrs = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 15)]
    let boldAttrs = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 15)]

    let partOne = NSMutableAttributedString(string: "Your score is ", attributes: normalAttrs)
    let partTwo = NSMutableAttributedString(string: "perfect".localized(), attributes: boldAttrs)
    let partThree = NSMutableAttributedString(string: ".", attributes: normalAttrs)

    partOne.append(partTwo)
    partOne.append(partThree)

    myLabel.attributedText = partOne

编辑:

这是使用NSMutableAttributedString

更为灵活的方法
replaceCharacters(in range: NSRange, with attrString: NSAttributedString)

无论长度或位置如何,这都可以轻松地用“得分词”的本地化版本替换本地化字符串中的"%@"

class TestViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // simulate localized strings
        let localizedStrings = [
            "Your score is %@.",
            "You got a %@ score.",
            "%@ is your final score.",
            ]

        let localizedPerfects = [
            "Perfect",
            "Perfekt",
            "Perfectamente",
            ]

        let normalAttrs = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 15)]
        let boldAttrs = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 15)]

        var y = 40

        for (scoreString, perfectString) in zip(localizedStrings, localizedPerfects) {

            // add a label
            let label = UILabel()
            view.addSubview(label)
            label.frame = CGRect(x: 20, y: y, width: 280, height: 40);
            y += 40

            if let rangeOfPctAt = scoreString.range(of: "%@") {

                let attStr = NSMutableAttributedString(string: scoreString, attributes: normalAttrs)
                let attPerfect = NSAttributedString(string: perfectString, attributes: boldAttrs)

                let nsRange = NSRange(rangeOfPctAt, in: attStr.string)
                attStr.replaceCharacters(in: nsRange, with: attPerfect)

                label.attributedText = attStr

            } else {

                // "%@" was not in localized score string
                label.text = "invalid score string format"

            }

        }

    }
}

结果:

enter image description here