1

I need to convert a string with some delimiters to an attributed string. My delimiters are $$italic$$ and $$$bold$$$. Actually, my code is functionnal only if I do not combine italic and bold. My trouble is $$$$$bold AND italic$$$$$. Only italic is set...

Here is my code in the UIViewcontroller Class :

func pikipiki2AttributedString(text: String) -> NSAttributedString {
    let attributedText = NSMutableAttributedString(string: text)
    let size = [NSFontAttributeName : UIFont.systemFontOfSize(15.0)]
    attributedText.addAttributes(size, range: NSRange(location: 0, length: attributedText.length))

    let attributeBold = [NSFontAttributeName: UIFont.boldSystemFontOfSize(15)]
    try! attributedText.addAttributes(attributeBold, delimiter: "$$$")

    let attributeItalic = [NSFontAttributeName: UIFont.italicSystemFontOfSize(15)]
    try! attributedText.addAttributes(attributeItalic, delimiter: "$$")

    return attributedText
}

And an extension founded here :

public extension NSMutableAttributedString {
    func addAttributes(attrs: [String : AnyObject], delimiter: String) throws {
        let escaped = NSRegularExpression.escapedPatternForString(delimiter)
        let regex = try NSRegularExpression(pattern:"\(escaped)(.*?)\(escaped)", options: [])

        var offset = 0
        regex.enumerateMatchesInString(string, options: [], range: NSRange(location: 0, length: string.characters.count)) { (result, flags, stop) -> Void in
            guard let result = result else {
                return
            }

            let range = NSRange(location: result.range.location + offset, length: result.range.length)enter code here
            self.addAttributes(attrs, range: range)
            let replacement = regex.replacementStringForResult(result, inString: self.string, offset: offset, template: "$1")
            self.replaceCharactersInRange(range, withString: replacement)
            offset -= (2 * delimiter.characters.count)
        }
    }
}
Community
  • 1
  • 1

0 Answers0