Usually I build app interface in interface builder. Sometimes design requires to use attributed strings (fonts, colors and etc.). It's easy to configure if string is static.
But if string is dynamic (format with arguments) then there are no ways to configure attributes in interface builder. It requires to write a lot of code.
I am looking for some analogues of [NSString stringWithFormat:]
for NSAttributedString
. So I will be able to set string format and necessary attributes in interface builder, and then provide necessary arguments in code.
For example:
Let's consider that I need display string with such format: "%d + %d = %d" (all numbers are bold).
I want to configure this format in interface builder. In code I want to provide arguments: 1, 1, 2. App should show "1 + 1 = 2".
The NSAttributedString type represents a string that has a series of attributes applied uniformly. The companion NSMutableAttributedString type can be used to create attributed strings that have overlapping attributes and whose contents can be modified after creation.
The companion NSMutableAttributedStringtype can be used to create attributed strings that have overlapping attributes and whose contents can be modified after creation.
To create NSAttributedStrings that you can use with UIKit's rendering, you create an instance of the UIStringAttributesclass, set its properties to the attributes that you desire, and then invoke the NSAttributedString constructor with it.
Substring(nint, nint) ToString() Returns a string representation of the value of the current instance. (Inherited from NSObject) Unbind(NSString) (Inherited from NSObject) Unbind(String) Obsolete. (Inherited from NSObject) ValueForKey(NSString) Returns the value of the property associated with the specified key.
Compatible with Swift 4.2
public extension NSAttributedString {
convenience init(format: NSAttributedString, args: NSAttributedString...) {
let mutableNSAttributedString = NSMutableAttributedString(attributedString: format)
args.forEach { (attributedString) in
let range = NSString(string: mutableNSAttributedString.string).range(of: "%@")
mutableNSAttributedString.replaceCharacters(in: range, with: attributedString)
}
self.init(attributedString: mutableNSAttributedString)
}
}
Usage:
let content = NSAttributedString(string: "The quick brown %@ jumps over the lazy %@")
let fox = NSAttributedString(string: "fox", attributes: [.font: Fonts.CalibreReact.boldItalic.font(size: 40)])
let dog = NSAttributedString(string: "dog", attributes: [.font: Fonts.CalibreReact.lightItalic.font(size: 11)])
attributedLabel.attributedText = NSAttributedString(format: content, args: fox, dog)
Result:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With