您需要创建一个指定居中对齐的段落样式,并将该段落样式设置为文本的属性.操场示例:
import UIKit
import PlaygroundSupport
let style = NSMutableParagraphStyle()
style.alignment = NSTextAlignment.center
let richText = NSMutableAttributedString(string: "Going through some basic improvements to a application I am working on. Still new to the iOS swift development scene. I figured that the lines of text in my code would automatically be centered because I set the label to center.",
attributes: [ NSParagraphStyleAttributeName: style ])
// In Swift 4, use `.paragraphStyle` instead of `NSParagraphStyleAttributeName`.
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 400))
label.backgroundColor = UIColor.white
label.attributedText = richText
label.numberOfLines = 0
PlaygroundPage.current.liveView = label
结果:
由于要分析HTML文档以创建属性字符串,因此需要在创建后添加属性,如下所示:
let style = NSMutableParagraphStyle()
style.alignment = NSTextAlignment.center
let richText = try NSMutableAttributedString(
data: assetDetails!.cardDescription.data(using: String.Encoding.utf8)!,
options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType],
documentAttributes: nil)
richText.addAttributes([ NSParagraphStyleAttributeName: style ],
range: NSMakeRange(0, richText.length))
// In Swift 4, use `.paragraphStyle` instead of `NSParagraphStyleAttributeName`.
assetDescription.attributedText = richText
Swift 4更新
在Swift 4中,属性名称现在是类型NSAttributeStringKey
,标准属性名称是该类型的静态成员.因此,可以添加如下属性:
richText.addAttribute(.paragraphStyle, value: style, range: NSMakeRange(0, richText.length))