Use AttributedString in SwiftUI Before iOS 15
Surely Nobody Needs To?
--
The Problem
Before iOS 15 AttributedString for SwiftUI wasn’t a thing. Something which might produce the following result:
If you wish to have a String with text (perhaps part of the text has colour and part has a size) you might need to come up with a solution. Such a String might be:
var message: AttributedString {
var redString = AttributedString("Is this red?")
redString.font = .systemFont(ofSize: 18)
redString.foregroundColor = .red
var largeString = AttributedString("This should be larger!")
largeString.font = .systemFont(ofSize: 24)
return redString + largeString
}
How hard can it be?
In iOS 15 we would have:
Text(message)
But that initializer isn’t available. What should we do? We would probably have the following:
HStack {
Text("Is this red?")
.font(.system(size: 18))
.foregroundColor(.red)
Text("This should be larger!")
.font(.system(size: 24))
}
It’s quite messy isn’t it? Doesn’t use the NSAttributedString. Quite verbose. So what should we do?
Oh, the NSAttributedString
can look something like the following:
var messageAttributed: NSAttributedString {
let redString = NSMutableAttributedString(string: "Is this red? ", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])
let largeString = NSAttributedString(string: "This should be larger!", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 24)])
redString.append(largeString)
return redString
}
The Solution
This might not be the only possible solution. It is a solution though!
If it’s available use the iOS 15 attributed String.
public extension Text {
init(_ attributedString: NSAttributedString) {
if #available(iOS 15.0, *) {…