在 iOS 中,NSAttributedString 是一种用于在文本中添加样式和属性的类。你可以使用 NSAttributedString 来设置文本的字体、颜色、行间距、下划线等属性。
下面是如何使用 NSAttributedString 的一个示例:
// 创建一个 NSMutableAttributedString 对象let attributedString = NSMutableAttributedString(string: "Hello, World!")// 设置文本的字体和颜色let attributes: [NSAttributedString.Key: Any] = [ .font: UIFont.systemFont(ofSize: 20), .foregroundColor: UIColor.red]attributedString.addAttributes(attributes, range: NSRange(location: 0, length: attributedString.length))// 设置文本的下划线let underlineAttributes: [NSAttributedString.Key: Any] = [ .underlineStyle: NSUnderlineStyle.single.rawValue]attributedString.addAttributes(underlineAttributes, range: NSRange(location: 0, length: 5))// 设置文本的行间距let paragraphStyle = NSMutableParagraphStyle()paragraphStyle.lineSpacing = 5attributedString.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attributedString.length))// 将 NSAttributedString 应用到 UILabel 中let label = UILabel()label.attributedText = attributedString在上面的示例中,我们首先创建了一个 NSMutableAttributedString 对象,并设置了一些属性,最后将这些属性应用到了一个 UILabel 中。
通过使用 NSAttributedString,你可以轻松地在文本中添加各种样式和属性,使你的应用界面更加丰富和美观。




