我有一個字串,假設“我的名字是 %@,我在 %@ 班學習”現在我想將要插入的占位符文本加粗,以便結果看起來像這樣:“我的名字是Harsh和我在第10班學習“我會在標簽上顯示
我已經嘗試過使用 NSAttributedString 但由于字串將被本地化,我無法使用屬性字串的范圍引數使其變為粗體。
uj5u.com熱心網友回復:
這應該有效:
- 使用占位符獲取本地化字串
- 查找該字串中占位符的位置(您可能需要編號的占位符)
- 確定將替換占位符的值的長度
- 通過替換占位符展開字串
- 計算擴展字串中值的范圍
- 加粗
uj5u.com熱心網友回復:
我可以提供一個解決方案,NSRegularExpression盡管它確實不使用任何復雜的運算式。
這些步驟與上面發布的含義非常接近
- 將要注入的字串(Harsh,13)等存盤在陣列中
- 有一個包含占位符的本地化字串
- 使用 REGEX 查找占位符的位置并將這些位置存盤在
locations array - 通過將占位符替換為字串陣列中的值來更新本地化字串
NSMutableAttributedString從更新的本地化字串創建- 回圈遍歷字串以注入陣列并更新
NSMutableAttributedString由locations array
這是我用一些注釋來解釋的代碼:
// This is not needed, just part of my UI
// Only the inject part is relevant to you
@objc
private func didTapSubmitButton()
{
if let inputText = textField.text
{
let input = inputText.components(separatedBy: ",")
let text = "My name is %@ and I am %@ years old"
inject(input, into: text)
}
}
// The actual function
private func inject(_ strings: [String],
into text: String)
{
let placeholderString = "%@"
// Store all the positions of the %@ in the string
var placeholderIndexes: [Int] = []
// Locate the %@ in the original text
do
{
let regex = try NSRegularExpression(pattern: placeholderString,
options: .caseInsensitive)
// Loop through all the %@ found and store their locations
for match in regex.matches(in: text,
options: NSRegularExpression.MatchingOptions(),
range: NSRange(location: 0,
length: text.count))
as [NSTextCheckingResult]
{
// Append your placeholder array with the location
placeholderIndexes.append(match.range.location)
}
}
catch
{
// handle errors
print("error")
}
// Expand your string by inserting the parameters
let updatedText = String(format: text, arguments: strings)
// Configure an NSMutableAttributedString with the updated text
let attributedText = NSMutableAttributedString(string: updatedText)
// Keep track of an offset
// Initially when you store the locations of the %@ in the text
// My name is %@ and my age is %@ years old, the location is 11 and 27
// But when you add Harsh, the next location should be increased by
// the difference in length between the placeholder and the previous
// string to get the right location of the second parameter
var offset = 0
// Loop through the strings you want to insert
for (index, parameter) in strings.enumerated()
{
// Get the corresponding location of where it was inserted
// Plus the offset as discussed above
let locationOfString = placeholderIndexes[index] offset
// Get the length of the string
let stringLength = parameter.count
// Create a range
let range = NSRange(location: locationOfString,
length: stringLength)
// Set the bold font
let boldFont
= UIFont.boldSystemFont(ofSize: displayLabel.font.pointSize)
// Set the attributes for the given range
attributedText.addAttribute(NSAttributedString.Key.font,
value: boldFont,
range: range)
// Update the offset as discussed above
offset = stringLength - placeholderString.count
}
// Do what you want with the string
displayLabel.attributedText = attributedText
}
最終結果:

這應該足夠靈活,可以處理字串中存在的任意數量的占位符,并且您不需要跟蹤不同的占位符。
uj5u.com熱心網友回復:
let descriptionString = String(format: "localised_key".localized(), Harsh, 10)
let description = NSMutableAttributedString(string: descriptionString, attributes: [NSAttributedString.Key.font: UIFont(name: "NotoSans-Regular", size: 15.7)!, NSAttributedString.Key.foregroundColor: UIColor(rgb: 0x000b38), NSAttributedString.Key.kern: 0.5])
let rangeName = descriptionString.range(of: "Harsh")
let rangeClass = descriptionString.range(of: "10")
let nsrangeName = NSRange(rangeName!, in: descriptionString)
let nsrangeClass = NSRange(rangeClass!, in: descriptionString)
description.addAttributes([NSAttributedString.Key.font: UIFont(name: "NotoSans-Bold", size: 15.7)!, NSAttributedString.Key.foregroundColor: UIColor(rgb: 0x000b38), NSAttributedString.Key.kern: 0.5], range: nsrangeName)
description.addAttributes([NSAttributedString.Key.font: UIFont(name: "NotoSans-Bold", size: 15.7)!, NSAttributedString.Key.foregroundColor: UIColor(rgb: 0x000b38), NSAttributedString.Key.kern: 0.5], range: nsrangeClass)
如需更多參考,請使用此
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/430540.html
