Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you stroke text using AttributedString in iOS 15?

iOS 15 includes support for AttributedString

Example

struct PlaygroundView: View {
    func attributedString(string: String) -> AttributedString {
        var text = AttributedString(string)
        text.font = .largeTitle.bold()
        text.foregroundColor = .blue
        return text
    }
    
    var body: some View {
        Text(attributedString(string: "Hello"))
    }
}

Attributed text

Documentation mentions Attribute Scopes

The AttributedString API defines keys for common uses, such as text styling, semantically marking up formattable types like dates and numbers, and hyperlinking. You can find these in the AttributeScopes enumeration, which contains attributes for Foundation, SwiftUI, UIKit, and AppKit.

Here's strokeColor for the stroke color attribute, but it appears to do nothing.

struct PlaygroundView: View {
    func attributedString(string: String) -> AttributedString {
        var text = AttributedString(string)
        text.font = .largeTitle.bold()
        text.foregroundColor = .blue
        text.strokeWidth = 5
        text.strokeColor = .red
        return text
    }
    
    var body: some View {
        Text(attributedString(string: "Hello"))
    }
}

Attributed text

Additional docs:

  • Foundation attributes https://developer.apple.com/documentation/foundation/attributescopes/foundationattributes

  • SwiftUI attributes https://developer.apple.com/documentation/foundation/attributescopes/swiftuiattributes

  • UIKit attributes https://developer.apple.com/documentation/foundation/attributescopes/uikitattributes

  • AppKit attributes https://developer.apple.com/documentation/foundation/attributescopes/appkitattributes

like image 587
Zelko Avatar asked Aug 29 '26 15:08

Zelko


1 Answers

strokeWidth in AttributedString doesn't work with SwiftUI.

I asked similar question on Twitter after WWDC 2021 and I got a reply from Foundation Engineer at Apple. This was the reply:

.strokeWidth is an AppKit/UIKit defined attribute so it isn’t guaranteed to work with SwiftUI automatically. You can find all of the attributes supported by SwiftUI at https://developer.apple.com/documentation/foundation/attributescopes/swiftuiattributes

If you want to use stroked text with SwiftUI, you will need to use UIViewRepresentable view as a workaround. Create a UILabel and set a NSAttributedString with strokeWidth to attributedText property of UILabel.

like image 104
rahulrs Avatar answered Sep 01 '26 05:09

rahulrs