2017-04-17 2 views
0

바꾸고 싶습니다 맞춤 내 HTML iOS Swift 3 Xcode 8.3에 있습니다.
모든 것들이 올바르게 작동하지만 정렬에 대해 잘 모르겠습니다. attributes. 이 같은
내 코드 :NSMutableAttributedString에서 정렬을 설정하는 방법 iOS Swift 3

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 
    } 
} 

답변

2

오류를 가져 오는 이유는 options 매개 변수 유형의 사전 있다는 것이다 : NSDocumentTypeDocumentAttribute (문자열)와 NSTextAlignment (INT) 불법를 전달 [String : Any] (사전 강력하게 입력되어있다) .

해결책은 NSMutableParagraphStyle을 사용하여 옵션으로 추가하는 것입니다. 이미 하나라고 선언되어 있으며, 정렬은 .center으로 설정되어 있지만 사용하지는 않았습니다! 다음과 같이

당신은 NSParagraphStyleAttributeName 키 (대신 NSTextAlignment을의)에 추가해야합니다 NSParagraphStyleAttributeName 데이터 형식 옵션 dictionary의 데이터 유형이 -legally- 될 것이라고 의미하는 문자열입니다

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 
    } 
} 

하는 것으로 [String : Any].

관련 문제