ios - 使用 NSAttributedString 在 UILabel 中居中文本

标签 ios swift uilabel nsattributedstring

对我正在开发的应用程序进行一些基本改进。仍然是 iOS 快速开发领域的新手。我认为我的代码中的文本行会自动居中,因为我将标签设置为居中。经过一些研究,我发现情况并非如此。我如何将这样的代码居中对齐:

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

最佳答案

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

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))

关于ios - 使用 NSAttributedString 在 UILabel 中居中文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33443017/

相关文章:

ios - iOS文件创建可访问所有应用程序

ios - 注释不会删除

ios - 核心数据并发调试

ios - 在实例化 UISwitcher 时尝试实例化 UILabel

ios - 如何以编程方式创建一个带有 UIWebView 的 UINavigationController?

javascript - React Native 如何防止键盘在文本提交时消失?

swift - 使用 Swift 3 在警告消息框标题中添加图像

ios - 点击后退按钮后,通过 segue 的数据丢失

ios - 如何从 UILabel 中删除三个点?

ios - TableViewCell 的 UILabel 在 reloadData 和 onClick 上改变位置