如何将 NSAttributedString 中的字符大小写更改为大写
我想将包含 RTFD 的 NSAttributedString 转换为大写,而不丢失现有字符和图形的属性。
谢谢,
I want to convert NSAttributedString containing RTFD to uppercase without losing attributes of existing characters and graphics.
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(2)
相对绾红妆2024-12-01 02:24:46
当您大写德语“ß”字符时,它会变成“SS”;因此范围发生变化。这可能会导致接受的答案崩溃。以下是我针对此案例的建议:
extension NSAttributedString {
func uppercased() -> NSAttributedString {
// Original NSAttributedString
let originalAttributedString = self
// Convert the attributed string to a regular string
let originalString = originalAttributedString.string
// Uppercase the string
let uppercasedString = originalString.uppercased()
// Create a new mutable attributed string with the uppercased string
let uppercasedAttributedString = NSMutableAttributedString(string: uppercasedString)
// Track the difference in length due to character count changes
var indexOffset = 0
originalAttributedString.enumerateAttributes(in: NSRange(location: 0, length: originalAttributedString.length),
options: []) { attributes, range, _ in
// Extract the substring from the original string for this range
let originalSubstring = originalAttributedString.attributedSubstring(from: range).string
// Uppercase the substring
let uppercasedSubstring = originalSubstring.uppercased()
// Calculate the difference in length between the original and uppercased substrings
let lengthDifference = uppercasedSubstring.count - originalSubstring.count
// Adjust the range for the uppercased string (apply indexOffset before adjustment)
let adjustedRange = NSRange(location: range.location + indexOffset, length: uppercasedSubstring.count)
// Apply attributes to the new range in the uppercased attributed string
uppercasedAttributedString.addAttributes(attributes, range: adjustedRange)
// Update the index offset for future ranges
indexOffset += lengthDifference
}
return uppercasedAttributedString
}
}
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
编辑:
@fluidsonic 是正确的,原始代码不正确。下面是 Swift 的更新版本,它将每个属性范围中的文本替换为该范围内字符串的大写版本。
原答案:
作用:
EDIT:
@fluidsonic Is correct that the original code is incorrect. Below is an updated version in Swift, that replaces the text in each attribute range with an uppercased version of the string in that range.
Original answer:
What this does:
NSString
method.