swift 中的多行多色属性文本

Multiline multicolor attributed text in swift

如何使用属性文本构建类似这样的内容?我尝试添加换行符 (\n),它没有用,只显示第一行并裁剪下两行,删除 \n 将在单行中显示两个部分:

let mutableAttributedString = NSMutableAttributedString()

let regularAttribute = [NSAttributedStringKey.font: UIFont(name: "Avenir-Light", size: 45.0), NSAttributedStringKey.foregroundColor: UIColor.yellow]
let boldAttribute = [NSAttributedStringKey.font: UIFont(name: "Avenir-Light", size: 25.0), NSAttributedStringKey.foregroundColor: UIColor.white]     

let mutableAttributedString2 = NSMutableAttributedString()
let boldAttributedString = NSAttributedString(string: "person", attributes: boldAttribute)
let regularAttributedString = NSAttributedString(string: "\(self.requestCount)", attributes: regularAttribute)
mutableAttributedString2.append(boldAttributedString)
mutableAttributedString2.append(NSAttributedString(string: "\n"))
mutableAttributedString2.append(regularAttributedString)

self.btnStatsPeople.setAttributedTitle(mutableAttributedString2, for: .normal)

UILabel 默认有一个line

This property controls the maximum number of lines to use in order to fit the label’s text into its bounding rectangle. The default value for this property is 1. To remove any maximum limit, and use as many lines as needed, set the value of this property to 0.

UIButton 创建默认的 UILabel。所以使用 0 行是解决你的问题的方法:

self.btnStatsPeople.titleLabel?.numberOfLines = 0