Swift 4 Label attributes

前端 未结 7 735
死守一世寂寞
死守一世寂寞 2020-12-31 09:14

I\'m moving from swift 3 to swift 4. I have UILabels that I am giving very specific text properties to the label. I\'m getting an \'unexpectedly found nil while unwrapping

7条回答
  •  长情又很酷
    2020-12-31 09:59

    let text = systolicString + " / " + diastolicString
    
    let newStr = NSMutableAttributedString(string: text)
    // I have static ranges, but you can also extract them dynamically
    let systolicRange = NSRange(location: 0, length: 2)
    let backslashRange = NSRange(location: 3, length: 1)
    let diastolicRange = NSRange(location: 5, length: 2)
    
    newStr.addAttribute(NSAttributedStringKey.font, value:  UIFont.ubuntuRegular(28), range: systolicRange)
    newStr.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor(hexString: "042f57"), range: systolicRange)
    
    newStr.addAttribute(NSAttributedStringKey.font, value:  UIFont.ubuntuLight(23), range: backslashRange)
    newStr.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor(hexString: "6485a3"), range: backslashRange)
    
    newStr.addAttribute(NSAttributedStringKey.font, value:  UIFont.ubuntuRegular(18), range: diastolicRange)
    newStr.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor(hexString: "042f57"), range: diastolicRange)
    // my UILabel
    valueLabel.attributedText = newStr
    

提交回复
热议问题