1

I am trying to set custom/hex color of attributed string, But its not working. If I am setting system color like UIColor.red than its working, But If I set UIColor.init(hexString: "00008B") Than its not working.

My code snippet is-

let string = "\(model.username)     " + model.commentTitle as NSString

let attributedString = NSMutableAttributedString(string: string as String, attributes: [NSAttributedString.Key.font:UIFont(name: "Kohinoor Bangla", size: 15) ?? UIFont.systemFont(ofSize: 15.0)])
let rangeUsername = (string as NSString).range(of: model.username)
let rangeCommentText = (string as NSString).range(of: model.commentTitle)


attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.init(hexString: "00008B"), range: rangeUsername) // Not Working
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.systemBlue.withAlphaComponent(0.5), range: rangeCommentText) // Its Working



let boldFontAttribute = [NSAttributedString.Key.font: UIFont(name: "Campton Bold", size: 16)]

// Part of string to be bold
attributedString.addAttributes(boldFontAttribute as [NSAttributedString.Key : Any], range: string.range(of: model.username))
cell.lblComment.attributedText = attributedString
EmilioPelaez
  • 18,758
  • 6
  • 46
  • 50
iDeveloper
  • 2,339
  • 2
  • 24
  • 38
  • It's not related to `NSAttributedString`, just to `UIColor`. Check the doc of `init(named:)` https://developer.apple.com/documentation/uikit/uicolor/2877380-init If you tried your `anyView.backgroundColor = UIColor(named: "00008B")` you would have seen it. Else see https://stackoverflow.com/questions/24263007/how-to-use-hex-color-values/24263296 – Larme Jul 28 '21 at 13:23
  • You will need to create your own method to use colors in hex notation. If you do not care about using objective-c libraries then I created one with such functionality some time ago: https://github.com/leszek-s/LSCategories – Leszek Szary Jul 28 '21 at 16:02

1 Answers1

1

Note: Original question was about

UIColor(named: "00008B")

OP has edited this out of the question.


Named colors are not hex colors. They designate the name of a color set you have added to your asset catalog.

You don't have a color set called 00008B in your asset catalog, because you did not create one. And if you did create one, it could be any color at all.

In short, there is no built in magic conversion between a hex string and a color. You could write an extension to do the conversion, but even then you would not use named. You could call it hexString but you would have to provide the code for it; that doesn't exist either.

matt
  • 515,959
  • 87
  • 875
  • 1,141