[英]How to set Alignment in NSMutableAttributedString iOS Swift 3
I want to change alignment of my html in iOS Swift 3 Xcode 8.3 . 我想在iOS Swift 3 Xcode 8.3中更改html的对齐方式 。
Every things works correctly but i do not know about alignment 一切正常,但我不知道对齐
.
。
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
}
}
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). 出现错误的原因是
options
参数是类型为[String : Any]
的字典,传递NSDocumentTypeDocumentAttribute
(String)和NSTextAlignment
(Int)是非法的(字典是强类型的)。
The solution would be to use NSMutableParagraphStyle
and add it as an option; 解决的办法是使用
NSMutableParagraphStyle
并将其添加为选项。 You are already declared one and set its alignment to .center
, but you are not using it! 您已经被声明为一个并将其对齐方式设置为
.center
,但是您没有使用它!
You should add it with NSParagraphStyleAttributeName
key (instead of NSTextAlignment
), as follows: 您应该使用
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
}
}
Note that NSParagraphStyleAttributeName
data type is String, which means that the data type of the options dictionary
would be -legally- [String : Any]
. 注意,
NSParagraphStyleAttributeName
数据类型为String,这意味着选项dictionary
的数据类型为-legally- [String : Any]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.