Search code examples
iosswiftalignmentnsmutableattributedstring

How to set Alignment in NSMutableAttributedString iOS Swift 3


I want to change alignment of my html in iOS Swift 3 Xcode 8.3.
Every things works correctly but i do not know about alignment attributes.
My code like this:

extension String {
    func htmlAttributedString() -> NSAttributedString? {
        guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }

        let style = NSMutableParagraphStyle()
        style.alignment = NSTextAlignment.center


        guard let html = try? NSMutableAttributedString(
            data: data,
            options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,NSTextAlignment:.center],
            documentAttributes:nil) else { return nil }


        return html
    }
}

Solution

  • The reason of getting the error is that options parameter is a dictionary of type: [String : Any], passing NSDocumentTypeDocumentAttribute (String) and NSTextAlignment (Int) is illegal (dictionaries are strongly typed).

    The solution would be to use NSMutableParagraphStyle and add it as an option; You are already declared one and set its alignment to .center, but you are not using it!

    You should add it with NSParagraphStyleAttributeName key (instead of NSTextAlignment), as follows:

    extension String {
        func htmlAttributedString() -> NSAttributedString? {
            guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
    
            let style = NSMutableParagraphStyle()
            style.alignment = NSTextAlignment.center
    
            guard let html = try? NSMutableAttributedString(
                data: data,
                options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                          NSParagraphStyleAttributeName: style],
    
                documentAttributes:nil) else { return nil }
    
            return html
        }
    }
    

    Note that NSParagraphStyleAttributeName data type is String, which means that the data type of the options dictionary would be -legally- [String : Any].