在字符串中创建占位符值的属性文本

时间:2019-06-27 18:47:15

标签: swift nsattributedstring

我得到了这个http://www.starcitygames.com/buylist/search?search-type=name&name=game

String

我想将let someString = String(format: NSLocalizedString("%1$@ changed your user role %2$@.", comment: ""), username, userRole) 设为粗体。可以使用userRole完成。为了完成该任务,我认为需要创建替换文本的范围。除了添加标记(例如HTML标记)以识别占位符外,我不知道该怎么做。我不想使用标签,因为这将需要客户端/服务器端验证等。

有什么办法可以获取第二个参数的替换文本范围?仅在NSMutableAttributedString中搜索占位符是不够的,因为例如,如果用户角色等于占位符之前的翻译文本,则会得到错误的范围。

我希望有一种未来和用户证明的方式来使占位符文本归因于

1 个答案:

答案 0 :(得分:0)

出于方便的原因,我之前必须做这件事。我的策略是制作UILabel的子类,然后覆盖text成员,修改文本并设置标签的attributedText(有效覆盖原始文本)。像这样:

/// Custom label that autoformats its text content. Use "@" to denote bolded ranges.
class AutoformatLabel: UILabel {

    // The special char that denotes bolded ranges.
    private let kSpecialChar: String = "@"
    // Set your font size and which fonts you want to use for bold/regular, here.
    var boldedFont = UIFont.boldSystemFont(ofSize: 18.0)
    var regularFont = UIFont.systemFont(ofSize: 18.0)


    /// Usage:
    ///     label.text = "Regular text @bolded text@ back to regular"
    public override var text: String? {
        didSet {
            let attributedText = NSMutableAttributedString(string: "")
            let paragraphStyle = NSMutableParagraphStyle()
            // Add things like line spacing, etc. to your paragraphStyle here, if desired.
            paragraphStyle.alignment = self.textAlignment
            let phrases = text!.split(separator: kSpecialChar)
            for i in 0...(phrases.count - 1) {
                let attPhrase = NSMutableAttributedString(string: String(phrases[i]))
                if i % 2 != 0 {
                    attPhrase.addAttribute(NSAttributedStringKey.font, value: boldedFont, range: NSRange(location: 0, length: attPhrase.length))
                } else {
                    attPhrase.addAttribute(NSAttributedStringKey.font, value: regularFont, range: NSRange(location: 0, length: attPhrase.length))
                }
                attributedText.append(attPhrase)
            }
            attributedText.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attributedText.length - 1))
            self.attributedText = attributedText
        }
    }

}

您可以通过将常量kSpecialChar设置为任意值来更改表示粗体显示范围的字符。希望有帮助!


编辑:误读了该问题!这是您要查找的代码块:

let text = "changed your user role"
let boldedText = "user"
let boldedRange = text.range(of: "user")
let attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(NSAttributedStringKey.font, value: boldedFont, range: NSRange(location: boldedRange.lowerBound, length: boldedRange.upperBound - boldedRange.lowerBound))

myLabel.attributedText = attributedText