UILabel不显示属性文本

时间:2017-02-13 10:55:44

标签: ios swift swift3

我正在设置代码中的属性文本。在故事板中配置infoLabel字体系列和大小。 infoLabel包含3行文字。

以下是它的样子:

Labels with 3 lines of text. Some parts of it coloured

正在生成什么代码:

Label with text: 78 days{}{}...

let daysCount: Int = 78
let weight: Double = -3.8
let fitness: Int = 44 // Percent

var daysWord = NSAttributedString(string: NSLocalizedString("days", comment: "Comparison label line 1"))
if daysCount == 1 {
    daysWord = NSAttributedString(string: NSLocalizedString("day", comment: "Comparison label line 1"))
}
let firstLine = NSAttributedString(string: "\(daysCount) \(daysWord)")

let weightString = NSLocalizedString("\(weight) kg", comment: "Comparison label line 2")
let weightAttributes: [String : Any] = [NSForegroundColorAttributeName : UIColor.geGreenyBlue]
let attrubutedWeight = NSAttributedString(string: weightString, attributes: weightAttributes)
let secondLine = NSAttributedString(string: NSLocalizedString("weight: \(attrubutedWeight)", comment: "Comparison label line 2"))

let thirdLine = NSAttributedString(string: "")
infoLabel.attributedText = NSAttributedString(string: "\(firstLine)\n \(secondLine)\n \(thirdLine)")

当我在Storyboard中设置单一的深灰色文本时,它看起来不错,但是当我用代码更改它时,它会为它添加花括号。

1 个答案:

答案 0 :(得分:1)

您的代码存在很多问题。您还没有正确设置NSAttributedString,最后您甚至没有正确组合多个NSAttributedString。它应该是这样的。

let daysCount: Int = 78
let weight: Double = -3.8
let fitness: Int = 44 // Percent

var daysWord = "days"
if daysCount == 1 {
    daysWord = "day"
}

let firstLine = NSAttributedString(string: "\(daysCount) \(daysWord)")

//For Weight
let weightAttrStr = NSAttributedString(string: "weight: ")
let weightAttributes: [String : Any] = [NSForegroundColorAttributeName : UIColor. geGreenyBlue]
let attrubutedWeight = NSAttributedString(string: "\(weight) kg", attributes: weightAttributes)

//For Fitness
let fitnessAttrStr = NSAttributedString(string: "fitness: ")
let fitnessAttributes: [String : Any] = [NSForegroundColorAttributeName : UIColor. geGreenyBlue]
let attrubutedFitness = NSAttributedString(string: "+\(fitness)%", attributes: fitnessAttributes)

//Now Combine all the attributed with \n
let combineAttr = NSMutableAttributedString()
combineAttr.append(firstLine)
combineAttr.append(NSAttributedString(string: "\n"))
combineAttr.append(weightAttrStr)
combineAttr.append(attrubutedWeight)

combineAttr.append(NSAttributedString(string: "\n"))
combineAttr.append(fitnessAttrStr)
combineAttr.append(attrubutedFitness)

//Now set textAligment to center
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center
let attributes: [String : Any] = [NSParagraphStyleAttributeName: paragraph]
combineAttr.addAttributes(attributes, range: NSRange(location: 0, length: combineAttr.string.characters.count))

//Now set the combine attributedString to label
infoLabel.attributedText = combineAttr