Swift 3.0 method to set the UILabel number color to red

  • 2020-05-24 06:18:29
  • OfStack

Implementation requirements

This article comes from a question of group friends: how to display the number "note: this product can only be shipped as a whole (multiple of 12), 1 bag has been selected, and 11 bags are still needed" in red in UILabel?

Implementation approach

We can use UILabel's attribute string property to get the range of Numbers through regular expression matching, and then add the corresponding attribute.

The implementation code

The following is the implementation code, written using swift 3.0:


// Change the text color according to the regular expression 
func changeTextChange(regex: String, text: String, color: UIColor) -> NSMutableAttributedString
{
 let attributeString = NSMutableAttributedString(string: text)
 do {
  let regexExpression = try NSRegularExpression(pattern: regex, options: NSRegularExpression.Options())
  let result = regexExpression.matches(in: text, options: NSRegularExpression.MatchingOptions(), range: NSMakeRange(0, text.characters.count))
  for item in result {
   attributeString.addAttribute(NSForegroundColorAttributeName, value: color, range: item.range)
  }
 } catch {
  print("Failed with error: \(error)")
 }
 return attributeString
}
let text = " Note: this product can only be sold in one piece (12 Multiple delivery ), The selected 1 bag , worse 11 bag "
let renderLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 800, height: 30))
renderLabel.textAlignment = NSTextAlignment.center
renderLabel.backgroundColor = UIColor.lightGray
renderLabel.font = UIFont.boldSystemFont(ofSize: 20)
renderLabel.attributedText = changeTextChange(regex: "\\d+", text: text, color: UIColor.red)

You can run this code in playground.

Of course, you can do this without using regular expressions and in other ways, but regular expressions are flexible and can be implemented if you have new requirements.

conclusion


Related articles: