diff --git a/MastodonSDK/Sources/MastodonUI/Extension/NSAttributedString+Format.swift b/MastodonSDK/Sources/MastodonUI/Extension/NSAttributedString+Format.swift index 9eed1a595..786815c40 100644 --- a/MastodonSDK/Sources/MastodonUI/Extension/NSAttributedString+Format.swift +++ b/MastodonSDK/Sources/MastodonUI/Extension/NSAttributedString+Format.swift @@ -6,11 +6,42 @@ public extension NSAttributedString { convenience init(format: NSAttributedString, args: NSAttributedString...) { let mutableNSAttributedString = NSMutableAttributedString(attributedString: format) - args.forEach { attributedString in - let range = NSString(string: mutableNSAttributedString.string).range(of: "%@") - mutableNSAttributedString.replaceCharacters(in: range, with: attributedString) + zip(format.string.ranges(of: "%@"), Array(args)).forEach { range, arg in + mutableNSAttributedString.replaceCharacters(in: .init(range: range, originalText: format.string), with: arg) } - + self.init(attributedString: mutableNSAttributedString) } } + +private extension String { + func ranges(of searchString: String) -> [Range] { + let indices = indices(of: searchString) + let count = searchString.count + return indices.map({ index(startIndex, offsetBy: $0).. [Int] { + var indices = [Int]() + var position = startIndex + while let range = range(of: occurrence, range: position.., originalText: String) { + self.init( + location: range.lowerBound.utf16Offset(in: originalText), + length: range.upperBound.utf16Offset(in: originalText) - range.lowerBound.utf16Offset(in: originalText) + ) + } +}