swift中的多行多色属性文本

问题描述 投票:0回答:1

如何使用属性文本构建这样的东西?我尝试添加换行符(\ 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)
swift nsattributedstring
1个回答
1
投票

UILabel默认有一个line

此属性控制使用的最大行数,以使标签的文本适合其边界矩形。此属性的默认值为1.要删除任何最大限​​制,并根据需要使用尽可能多的行,请将此属性的值设置为0。

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

self.btnStatsPeople.titleLabel?.numberOfLines = 0
© www.soinside.com 2019 - 2024. All rights reserved.