From f63b56bbf2be0e59b2cbe1e9d8d179d6ebf05abb Mon Sep 17 00:00:00 2001 From: Marcus Kida Date: Fri, 5 May 2023 14:48:02 +0200 Subject: [PATCH] Make NSAttributedString extension allow multiple palceholder string replacements (IOS-140) --- .../Extension/NSAttributedString+Format.swift | 39 +++++++++++++++++-- 1 file changed, 35 insertions(+), 4 deletions(-) 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) + ) + } +}