如何在 NSMutableAttributedString iOS Swift 中设置对齐方式 3
How to set Alignment in NSMutableAttributedString iOS Swift 3
我想在 iOS Swift 3 Xcode 8.3 中更改 html 的 对齐方式 .
一切正常,但我不知道对齐 .
我的代码是这样的:
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
}
}
出现错误的原因是options
参数是一个类型为[String : Any]
的字典,传递NSDocumentTypeDocumentAttribute
(String)和NSTextAlignment
(Int)是非法(字典是强类型的)。
解决方案是使用 NSMutableParagraphStyle
并将其添加为选项;您已经声明了一个并将其对齐设置为 .center
,但您没有使用它!
你应该用NSParagraphStyleAttributeName
键添加它(而不是NSTextAlignment
),如下:
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
}
}
请注意,NSParagraphStyleAttributeName
数据类型是字符串,这意味着选项 dictionary
的数据类型将是合法的 [String : Any]
.
我想在 iOS Swift 3 Xcode 8.3 中更改 html 的 对齐方式 .
一切正常,但我不知道对齐
我的代码是这样的:
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
}
}
出现错误的原因是options
参数是一个类型为[String : Any]
的字典,传递NSDocumentTypeDocumentAttribute
(String)和NSTextAlignment
(Int)是非法(字典是强类型的)。
解决方案是使用 NSMutableParagraphStyle
并将其添加为选项;您已经声明了一个并将其对齐设置为 .center
,但您没有使用它!
你应该用NSParagraphStyleAttributeName
键添加它(而不是NSTextAlignment
),如下:
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
}
}
请注意,NSParagraphStyleAttributeName
数据类型是字符串,这意味着选项 dictionary
的数据类型将是合法的 [String : Any]
.