正在对我正在开发的应用程序进行一些基本的改进.对于iOS swift开发场景来说仍然是 fresh 事.我认为我的代码会自动居中.经过一点研究,我发现事实并非如此.我如何将这样的代码与中心对齐:

let atrString = try NSAttributedString(
   data: assetDetails!.cardDescription.dataUsingEncoding(NSUTF8StringEncoding)!, 
   options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType], 
   documentAttributes: nil)
assetDescription.attributedText = atrString

推荐答案

您需要创建一个指定居中对齐的段落样式,并将该段落样式设置为文本的属性.操场示例:

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

结果:

centered text in 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))

Swift相关问答推荐

可编码:将字符串解码为自定义类型(ISO 8601日期,无时间组件)

在swift静态var扩展中,如何或可以访问和返回具体类?

数据不会被ARC删除在swift'

在解码字符串时需要帮助.

如何在枚举有关联数据时使用combined if with case

Result类型的初始值设定项失败?

Swift ui 转换无法按预期工作

字符串和整数格式的for循环,帮忙!

如何使用 Swift 在非本地函数中切换()一个 Bool?

领域异常中的相同方法:发送到实例的无法识别的 Select 器

RxSwift 中 Single.just(...) 和 Observable.just(...) 之间有区别吗?

try 制作一个 Swift 扩展来替换字符串中的多次出现

与 SwiftUI 中的 onChange 修饰符相比,objectWillChangeSequence 的目的是什么?

在 SwiftUI 中的 ForEach 中使用 id 时如何为数组设置动画索引

任何使 ScrollView 像 List 一样执行更灵活的修饰符?

Swift:withCheckedContinuation 和 Dispatch QoSClass

让我的函数计算数组 Swift 的平均值

如何从元组数组创建字典?

如何在 Swift 中将对象归零

swift中相同的数据类型多变量声明