I am trying to make a simple Coffee Calculator. I need to display the amount of coffee in grams. The \"g\" symbol for grams needs to be attached to my UILabel that I am usin
Swifter Swift has a pretty sweet way to do this without any work really. Just provide the pattern that should be matched and what attributes to apply to it. They're great for a lot of things check them out.
``` Swift
let defaultGenreText = NSAttributedString(string: "Select Genre - Required")
let redGenreText = defaultGenreText.applying(attributes: [NSAttributedString.Key.foregroundColor : UIColor.red], toRangesMatching: "Required")
``
If you have multiple places where this would be applied and you only want it to happen for specific instances then this method wouldn't work.
You can do this in one step, just easier to read when separated.
Swift 4.2
extension UILabel {
func boldSubstring(_ substr: String) {
guard substr.isEmpty == false,
let text = attributedText,
let range = text.string.range(of: substr, options: .caseInsensitive) else {
return
}
let attr = NSMutableAttributedString(attributedString: text)
let start = text.string.distance(from: text.string.startIndex, to: range.lowerBound)
let length = text.string.distance(from: range.lowerBound, to: range.upperBound)
attr.addAttributes([NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: self.font.pointSize)],
range: NSMakeRange(start, length))
attributedText = attr
}
}
Swift 4.x
let attr = [NSForegroundColorAttributeName:self.configuration.settingsColor, NSFontAttributeName: self.configuration.settingsFont]
let title = NSAttributedString(string: self.configuration.settingsTitle,
attributes: attr)
Swift 3.0 // create attributed string
Define attributes like
let attributes = [NSAttributedStringKey.font : UIFont.init(name: "Avenir-Medium", size: 13.0)]
Swift: xcode 6.1
let font:UIFont? = UIFont(name: "Arial", size: 12.0)
let attrString = NSAttributedString(
string: titleData,
attributes: NSDictionary(
object: font!,
forKey: NSFontAttributeName))
Use this sample code. This is very short code to achieve your requirement. This is working for me.
let attributes = [NSAttributedStringKey.font : UIFont(name: CustomFont.NAME_REGULAR.rawValue, size: CustomFontSize.SURVEY_FORM_LABEL_SIZE.rawValue)!]
let attributedString : NSAttributedString = NSAttributedString(string: messageString, attributes: attributes)