Last active
July 28, 2020 20:54
-
-
Save backslash-f/b909ce1fd537824cb0f0c6ddaaa5000f to your computer and use it in GitHub Desktop.
NSMutableString Playground - change portions of it based on custom tags
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import UIKit | |
// Say you have a NSMutableString like "<strikeStartTag>+ 6.99<strikeEndTag>" and need to strike through "+ 6.99". | |
extension String { | |
func firstRange(from start: String, to end: String?) -> Range<String.Index>? { | |
guard let lower = range(of: start)?.upperBound else { return nil } | |
guard let end = end else { return lower..<self.endIndex } | |
guard let upper = self[lower...].range(of: end)?.lowerBound else { return nil } | |
return lower..<upper | |
} | |
} | |
extension NSRange { | |
init(_ range: Range<String.Index>, in string: String) { | |
let location = range.lowerBound.utf16Offset(in: string) | |
self.init( | |
location: location, | |
length: range.upperBound.utf16Offset(in: string) - location | |
) | |
} | |
} | |
extension NSMutableAttributedString { | |
func remove(string: String) { | |
guard let stringRange = self.string.range(of: string) else { return } | |
mutableString.replaceCharacters(in: NSRange(stringRange, in: string), with: "") | |
} | |
} | |
let strikeStartTag = "<strikeStart>" | |
let strikeEndTag = "<strikeEnd>" | |
let additionalCostPrices = NSMutableAttributedString(string: "\(strikeStartTag)+ 6.99\(strikeEndTag)") | |
if let priceRange = additionalCostPrices.string.firstRange(from: strikeStartTag, to: strikeEndTag) { | |
additionalCostPrices.string[priceRange] | |
additionalCostPrices.addAttributes( | |
[ | |
NSAttributedString.Key.strikethroughStyle: NSUnderlineStyle.single.rawValue, | |
NSAttributedString.Key.strikethroughColor: UIColor.black | |
], | |
range: NSRange(priceRange, in: additionalCostPrices.string) | |
} | |
additionalCostPrices.remove(string: strikeStartTag) | |
additionalCostPrices.remove(string: strikeEndTag) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment