Search code examples
xcodeswifttextviewnsattributedstring

Attributes in String


I'm working with text. I have some arrays of ranges of text attributes, but when I'm applying italic to text which already has bold attributes, my bold attributes disappearing. How can I apply my attributes text to become boldItalic in this case? Or I should find an intersection of my bold and italic ranges to apply boldItalic attributes?

For example I have "This is my text" and I want to get "This is my text"

Sorry, for poor english. This is part of my code

func attributedArticleText ()-> NSMutableAttributedString {
    let attString = NSMutableAttributedString(attributedString:NSAttributedString(string: articleText))
    if let strong = attributes?.strong {
        for range in strong {
            attString.addAttributes([NSFontAttributeName : UIFont(name: "SFUIDisplay-Bold", size: 12.0)!], range: range.range())
        }
    }
    if let italic = attributes?.italic {
        for range in italic {
            attString.addAttributes([NSFontAttributeName : UIFont(name: "SFUIText-LightItalic", size: 12.0)!], range: range.range())
        }
    }
    if let underLined = attributes?.underline {
        for range in underLined {
            attString.addAttributes([NSUnderlineStyleAttributeName: 1], range: range.range())
        }
    }
    if let cross = attributes?.cross {
        for range in cross {
            attString.addAttributes([NSStrikethroughStyleAttributeName: 1], range: range.range())
        }
    }
    return attString
}

Solution

  • I found a solution, if somebody interested

    if let italic = attributes?.italic {
            for range in italic {
                attString.enumerateAttributesInRange(range.range(), options: NSAttributedStringEnumerationOptions(rawValue: 0), usingBlock: { (dict : [String : AnyObject], rangeNS : NSRange, _) -> Void in
                    if let font = dict["NSFont"] as? UIFont {
                        let descriptor = font.fontDescriptor()
                        if descriptor.symbolicTraits == .TraitBold {
                            attString.addAttributes([NSFontAttributeName : UIFont(name: "SFUIText-BoldItalic", size: 12.0)!], range: range.range())
                        } else {
                            attString.addAttributes([NSFontAttributeName : UIFont(name: "SFUIText-LightItalic", size: 12.0)!], range: range.range())
                        }
                    }
                })
            }
        }