我有一些本地化字符串标签,如 ,我必须用标签中的粗体替换普通文本。
我有类似的东西
< B个ENTER< / B个帐户详情
我需要这个
输入帐户详情
我正在寻找最好的方法。如果它有帮助,我可以用其他东西替换 ,例如$或者其他东西。
我现在有一些你可以在下面看到的内容,但是当我在一个标签中有多个 标签时,它有点令人毛骨悚然而且无法正常工作。
extension UILabel {
@IBInspectable var localizable: String {
get {
return self.text ?? ""
}
set {
self.text = NSLocalizedString(newValue, comment: "")
if let value = text {
if let firstRange = value.range(of: "<b>"),
let secondRange = value.range(of: "</b>") {
let startPos = value.distance(from: value.startIndex, to: firstRange.lowerBound)
let endPos = value.distance(from: value.startIndex, to: secondRange.upperBound)
let stringtoReplace = value.substring(from: startPos, to: endPos)
let newString = (stringtoReplace.replacingOccurrences(of: "<b>", with: "")).replacingOccurrences(of: "</b>", with: "")
self.text = (text?.replacingOccurrences(of: "<b>", with: ""))?.replacingOccurrences(of: "</b>", with: "")
if let attributedText = self.attributedText,
let font = UIFont(name: "HelveticaNeue-Bold", size: self.font.pointSize) {
let attributedStringToChange = NSMutableAttributedString(attributedString: attributedText)
attributedStringToChange.addAttribute(NSFontAttributeName, value: font, range: (attributedText.string as NSString).range(of: newString))
self.attributedText = attributedStringToChange
}
}
}
}
}
}