Goal: Stroke text in watchOS with SwiftUI
WKInterfaceLabel offers support for NSAttributedString via setAttributedText which offers simple and easy support to stroke text.
However, with a new project using SwiftUI, WKInterfaceLabel isn’t available outside of the nonexistent storyboard:
Do not subclass or create instances of this class yourself. Instead, define outlets in your interface controller class and connect them to the corresponding objects in your storyboard file.
open class WKInterfaceLabel : WKInterfaceObject {
open func setText(_ text: String?)
open func setTextColor(_ color: UIColor?)
open func setAttributedText(_ attributedText: NSAttributedString?)
}
‘init()’ is unavailable
So, how can we use NSAttributedString in watchOS with SwiftUI?
Side note:
Down the road, I expect the new AttributedString to reliably replace NSAttributedString, but as of watchOS 8 and iOS 15, AttributedString is broken and incomplete. This forces me to look for a solution to use NSAttributedString in watchOS with SwiftUI.
2
Answers
In latest swiftUI you can use
AttributedString
instead ofNSAttributedString
.Details how to use it you can find in apple documentation: https://developer.apple.com/documentation/foundation/attributedstring
But still you can use NSAttributedString in swiftUI app in case of wrapping original NSTextField(macos) / UITextField(IOS) controls
Sample for macos wrapper (it’s must be easy to rewrite) :
But still in most cases better to use native way for SwiftUI —
AttributedString
.The easiest way is to draw an image:
Then use it with Image()