Ответ 1
Вам нужно создать стиль абзаца, определяющий выравнивание центра, и установить этот стиль абзаца как атрибут вашего текста. Пример игровой площадки:
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))