### Install SwiftRichString with Carthage Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Add this entry to your Cartfile to manage the dependency via Carthage. ```ogdl github "malcommac/SwiftRichString" ``` -------------------------------- ### Install SwiftRichString with Swift Package Manager Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Include this dependency definition in your Package.swift file. ```swift dependencies: [ .package(url: "https://github.com/malcommac/SwiftRichString.git", from: "3.5.0") ] ``` -------------------------------- ### Install SwiftRichString with CocoaPods Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Add this line to your Podfile to include the library in your Cocoa project. ```ruby pod 'SwiftRichString' ``` -------------------------------- ### Custom Text Transform for Markdown Bold Source: https://context7.com/malcommac/swiftrichstring/llms.txt Implement custom text transformations using `.custom { text in ... }`. This example wraps text with markdown bold syntax. ```swift let markdownBoldStyle = Style { $0.font = SystemFonts.Helvetica_Bold.font(size: 14) $0.textTransforms = [ .custom { text in return "**\(text)**" } ] } ``` -------------------------------- ### Create and Apply a Basic Style Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Demonstrates how to create a Style object with custom font, color, and underline attributes, and then apply it to a string. ```swift let style = Style { $0.font = SystemFonts.AmericanTypewriter.font(size: 25) // just pass a string, one of the SystemFonts or an UIFont $0.color = "#0433FF" // you can use UIColor or HEX string! $0.underline = (.patternDot, UIColor.red) $0.alignment = .center } let attributedText = "Hello World!".set(style: style) // et voilà! ``` -------------------------------- ### Set Up Deferred Style Provider Source: https://context7.com/malcommac/swiftrichstring/llms.txt Configure a deferred style provider using `Styles.onDeferStyle`. This allows styles to be created on demand and optionally cached. ```swift Styles.onDeferStyle = { switch styleName { case "dynamicHeading": let style = Style { $0.font = UIFont.preferredFont(forTextStyle: .headline) $0.color = UIColor.label } return (style, true) // (style, shouldCache) case "error": let style = Style { $0.color = UIColor.systemRed $0.font = SystemFonts.Helvetica_Bold.font(size: 14) } return (style, true) default: return (nil, false) // Style not found } } ``` -------------------------------- ### Create a Style with Builder Pattern Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Illustrates the creation of a Style instance using a builder pattern, allowing for clean and readable configuration of font, color, and other attributes. ```swift let style = Style { $0.font = SystemFonts.Helvetica_Bold.font(size: 20) $0.color = UIColor.green // ... set any other attribute } let attrString = "Some text".set(style: style) // attributed string ``` -------------------------------- ### Set Colors with HEX Strings Source: https://context7.com/malcommac/swiftrichstring/llms.txt Shows how to apply colors using HEX strings or native UIColor instances. ```swift let colorfulStyle = Style { $0.font = SystemFonts.Helvetica_Light.font(size: 16) $0.color = "#0433FF" // Foreground color from HEX $0.backColor = "#FFEB3B" // Background color from HEX } // You can also use UIColor directly let alternateStyle = Style { $0.color = UIColor.systemBlue $0.backColor = UIColor.systemYellow.withAlphaComponent(0.3) } // Convert HEX string to UIColor let brandColor: UIColor = "#FF5722".color let styledText = "Colorful Text".set(style: colorfulStyle) ``` -------------------------------- ### Build Complex Greeting String Source: https://context7.com/malcommac/swiftrichstring/llms.txt Demonstrates building a complex greeting string by concatenating multiple styled and unstyled string parts. ```swift let username = "John" let greeting = "Hello, ".set(style: Style { $0.color = .gray }) + username.set(style: boldStyle) + "!" ``` -------------------------------- ### Set Font and Size Source: https://context7.com/malcommac/swiftrichstring/llms.txt Demonstrates various ways to specify fonts using enums, strings, or direct UIFont instances. ```swift // Using SystemFonts enum (type-safe) let style1 = Style { $0.font = SystemFonts.AmericanTypewriter.font(size: 18) } // Using font name string let style2 = Style { $0.font = "Helvetica-Bold" $0.size = 20 } // Using UIFont directly let style3 = Style { $0.font = UIFont.systemFont(ofSize: 16, weight: .medium) } // Convert string to font let customFont: UIFont = "FiraCode-Regular".font(ofSize: 14) let text = "Hello World".set(style: style1) ``` -------------------------------- ### Create a Basic Style Source: https://context7.com/malcommac/swiftrichstring/llms.txt Uses the builder pattern to define text attributes and apply them to a string. ```swift import SwiftRichString // Create a style using the builder pattern let headingStyle = Style { $0.font = SystemFonts.Helvetica_Bold.font(size: 24) $0.color = UIColor.darkText $0.alignment = .center $0.lineSpacing = 4 } // Apply style to a string let attributedHeading = "Welcome to SwiftRichString".set(style: headingStyle) // Use the attributed string in a label myLabel.attributedText = attributedHeading ``` -------------------------------- ### Manually set styles and attributed text Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Demonstrates manual application of styles and attributed strings to UI controls. ```swift // manually set the an attributed string self.label?.attributedText = (self.label?.text ?? "").set(myStyle) // manually set the style via instance self.label?.style = myStyle self.label?.styledText = "Updated text" ``` -------------------------------- ### Conforming to Dynamic Type Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Demonstrates how to support dynamic text scaling based on user preferences by implementing the `dynamicText` property within a `Style`, utilizing `UIFontMetrics`. ```APIDOC ### Conforming to `Dynamic Type` To support dynamic text scaling based on the user's preferred content size, implement a style's `dynamicText` property. `UIFontMetrics` properties are encapsulated within the `DynamicText` class. ```swift let style = Style { $0.font = UIFont.boldSystemFont(ofSize: 16.0) $0.dynamicText = DynamicText { $0.style = .body $0.maximumSize = 35.0 $0.traitCollection = UITraitCollection(userInterfaceIdiom: .phone) } } ``` ``` -------------------------------- ### Configure Paragraph Styling Source: https://context7.com/malcommac/swiftrichstring/llms.txt Sets paragraph-level attributes such as alignment, spacing, and indentation. ```swift let paragraphStyle = Style { $0.font = SystemFonts.Georgia.font(size: 14) $0.color = UIColor.darkText // Line and paragraph spacing $0.lineSpacing = 6 $0.paragraphSpacingBefore = 12 $0.paragraphSpacingAfter = 8 // Text alignment $0.alignment = .justified // Indentation $0.firstLineHeadIndent = 24 $0.headIndent = 0 $0.tailIndent = 0 // Line height control $0.minimumLineHeight = 20 $0.maximumLineHeight = 28 $0.lineHeightMultiple = 1.2 // Line breaking $0.lineBreakMode = .byWordWrapping // Hyphenation (0.0 to 1.0) $0.hyphenationFactor = 0.8 } let longText = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. """ let formattedParagraph = longText.set(style: paragraphStyle) ``` -------------------------------- ### Text Styling and Accessibility Attributes Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md A reference list of available configuration attributes for text styling, typography, and speech synthesis in SwiftRichString. ```APIDOC ## Text Styling Attributes ### Description List of properties used to configure text rendering, typography, and accessibility features. ### Attributes - **lineHeightMultiple** (CGFloat) - Natural line height multiplier. - **hyphenationFactor** (Float) - Threshold for hyphenation. - **ligatures** (Ligatures) - Character combination rendering. - **speaksPunctuation** (Bool) - Enable/disable punctuation in speech. - **speakingLanguage** (String) - BCP 47 language code for speech. - **speakingPitch** (Double) - Pitch for spoken content. - **speakingPronunciation** (String) - Pronunciation configuration. - **shouldQueueSpeechAnnouncement** (Bool) - Queueing behavior for speech. - **headingLevel** (HeadingLevel) - Heading level specification. - **numberCase** (NumberCase) - Figure style configuration. - **numberSpacing** (NumberSpacing) - Figure spacing configuration. - **fractions** (Fractions) - Fraction display configuration. - **superscript** (Bool) - Use superscript glyphs. - **subscript** (Bool) - Use subscript glyphs. - **ordinals** (Bool) - Use ordinal glyphs. - **scientificInferiors** (Bool) - Use scientific inferior glyphs. - **smallCaps** (Set) - Small caps configuration. - **stylisticAlternates** (StylisticAlternates) - Font stylistic alternates. - **contextualAlternates** (ContextualAlternates) - Font contextual alternates. - **kerning** (Kerning) - Tracking/kerning value. - **traitVariants** (TraitVariant) - Font trait variants. ``` -------------------------------- ### Use StandardXMLAttributesResolver for default tag support Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Demonstrates the default resolver which supports color attributes and anchor tags. ```swift let sourceHTML = "My webpage is really cool. Take a look here" let styleBase = Style({ $0.font = UIFont.boldSystemFont(ofSize: 15) }) let styleBold = Style({ $0.font = UIFont.boldSystemFont(ofSize: 20) $0.color = UIColor.blue }) let groupStyle = StyleXML.init(base: styleBase, ["b" : styleBold]) self.textView?.attributedText = sourceHTML.set(style: groupStyle) ``` -------------------------------- ### Derivating a Style Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Explains how to create a new `Style` by inheriting properties from an existing one using the `byAdding()` function, allowing for attribute overrides and additions. ```APIDOC ## Derivating a `Style` The `byAdding()` function of `Style` allows you to infer properties from an existing style to produce a new style. This new style inherits all attributes of the receiver and can be configured with additional or replacing attributes. ```swift let initialStyle = Style { $0.font = SystemFonts.Helvetica_Light.font(size: 15) $0.alignment = right } // The following style contains all the attributes of initialStyle // but also override the alignment and add a different foreground color. let subStyle = bold.byAdding { $0.alignment = center $0.color = UIColor.red } ``` ``` -------------------------------- ### Apply Underline and Strikethrough Source: https://context7.com/malcommac/swiftrichstring/llms.txt Configures text decorations with specific styles and colors. ```swift let decoratedStyle = Style { $0.font = SystemFonts.Helvetica.font(size: 16) // Underline with style and color $0.underline = (.single, UIColor.blue) // Strikethrough with style and color $0.strikethrough = (.double, UIColor.red) } // Pattern-based underline let dottedUnderlineStyle = Style { $0.font = SystemFonts.Helvetica.font(size: 16) $0.underline = (.patternDot, UIColor.gray) } // Strikethrough only (using foreground color) let crossedOutStyle = Style { $0.color = UIColor.gray $0.strikethrough = (.single, nil) // nil uses foreground color } let decoratedText = "Decorated Text".set(style: decoratedStyle) ``` -------------------------------- ### Apply styles to String & Attributed String Instances Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Convenience methods are available on String and AttributedString to easily apply styles. ```APIDOC ## Apply styles to `String` & `Attributed String` ### Description Both `String` and `Attributed String` (aka `NSMutableAttributedString`) offer convenience methods to create and manipulate attributed text easily via code. ### Strings Instance Methods - `set(style: String, range: NSRange? = nil)`: Apply a globally registered style to the string (or a substring) by producing an attributed string. - `set(styles: [String], range: NSRange? = nil)`: Apply an ordered sequence of globally registered styles to the string (or a substring) by producing an attributed string. - `set(style: StyleProtocol, range: NSRange? = nil)`: Apply an instance of `Style` or `StyleXML` (to render tag-based text) to the string (or a substring) by producing an attributed string. - `set(styles: [StyleProtocol], range: NSRange? = nil)`: Apply a sequence of `Style`/`StyleXML` instances in order to produce a single attributes collection which will be applied to the string (or substring) to produce an attributed string. ### Examples ```swift // Apply a globally registered style named MyStyle to the entire string let a1: AttributedString = "Hello world".set(style: "MyStyle") // Apply a style group to the entire string // commonStyle will be applied to the entire string as base style // styleH1 and styleH2 will be applied only for text inside that tags. let styleH1: Style = ... let styleH2: Style = ... let StyleXML = StyleXML(base: commonStyle, ["h1" : styleH1, "h2" : styleH2]) let a2: AttributedString = "Hello

world

,

welcome here

".set(style: StyleXML) // Apply a style defined via closure to a portion of the string let a3 = "Hello Guys!".set(Style({ $0.font = SystemFonts.Helvetica_Bold.font(size: 20) }), range: NSMakeRange(0,4)) ``` ``` -------------------------------- ### Apply styles with StyleXML Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Use StyleXML to define a base style and tag-specific styles for rendering tag-based strings. ```swift let bodyStyle: Style = ... let h1Style: Style = ... let h2Style: Style = ... let group = StyleXML(base: bodyStyle, ["h1": h1Style, "h2": h2Style]) let attrString = "Some

text

,

welcome here

".set(style: group) ``` -------------------------------- ### Register Global Styles with StylesManager Source: https://context7.com/malcommac/swiftrichstring/llms.txt Register styles globally using `Styles.register` for reuse across the application. Styles can be accessed by their registered name. ```swift struct StyleNames { static let heading = "heading" static let body = "body" static let caption = "caption" static let link = "link" } func setupStyles() { Styles.register(StyleNames.heading, style: Style { $0.font = SystemFonts.Helvetica_Bold.font(size: 24) $0.color = UIColor.label }) Styles.register(StyleNames.body, style: Style { $0.font = SystemFonts.Helvetica.font(size: 16) $0.color = UIColor.secondaryLabel $0.lineSpacing = 4 }) Styles.register(StyleNames.caption, style: Style { $0.font = SystemFonts.Helvetica_Light.font(size: 12) $0.color = UIColor.tertiaryLabel }) Styles.register(StyleNames.link, style: Style { $0.color = UIColor.systemBlue $0.underline = (.single, nil) }) } ``` -------------------------------- ### Configure Dynamic Type Support Source: https://context7.com/malcommac/swiftrichstring/llms.txt Enable automatic font scaling based on user accessibility settings using the DynamicText configuration. ```swift let accessibleStyle = Style { $0.font = UIFont.boldSystemFont(ofSize: 16) $0.color = UIColor.label // Configure Dynamic Type $0.dynamicText = DynamicText { $0.style = .body // Text style category $0.maximumSize = 28 // Maximum allowed size $0.traitCollection = UITraitCollection(userInterfaceIdiom: .phone) } } // Different text styles let headlineStyle = Style { $0.font = UIFont.preferredFont(forTextStyle: .headline) $0.dynamicText = DynamicText { $0.style = .headline $0.maximumSize = 36 } } let captionStyle = Style { $0.font = UIFont.preferredFont(forTextStyle: .caption1) $0.dynamicText = DynamicText { $0.style = .caption1 } } // Font automatically scales with user's preferred content size let scalableText = "Accessible Text".set(style: accessibleStyle) ``` -------------------------------- ### XML/HTML Tag Based String Rendering Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Shows how to define multiple styles (normal, bold, italic) and group them into a StyleXML object to render a string with embedded XML tags. This allows for complex styling within a single string. ```swift // Create your own styles let normal = Style { $0.font = SystemFonts.Helvetica_Light.font(size: 15) } bold = Style { $0.font = SystemFonts.Helvetica_Bold.font(size: 20) $0.color = UIColor.red $0.backColor = UIColor.yellow } let italic = normal.byAdding { $0.traitVariants = .italic } let myGroup = StyleXML(base: normal, ["bold": bold, "italic": italic]) let str = "Hello Daniele!. You're ready to play with us!" self.label?.attributedText = str.set(style: myGroup) ``` -------------------------------- ### Use Registered Styles by Name Source: https://context7.com/malcommac/swiftrichstring/llms.txt Apply globally registered styles to text by referencing their names. Multiple registered styles can be applied, and they will be merged. ```swift let headingText = "Page Title".set(style: StyleNames.heading) let bodyText = "Content goes here...".set(style: StyleNames.body) let mixedText = "Mixed styling".set(styles: [StyleNames.body, StyleNames.link]) ``` -------------------------------- ### Apply styles to String and Attributed String Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Use convenience methods like set(style:) to apply styles to strings or specific ranges. ```swift // apply a globally registered style named MyStyle to the entire string let a1: AttributedString = "Hello world".set(style: "MyStyle") // apply a style group to the entire string // commonStyle will be applied to the entire string as base style // styleH1 and styleH2 will be applied only for text inside that tags. let styleH1: Style = ... let styleH2: Style = ... let StyleXML = StyleXML(base: commonStyle, ["h1" : styleH1, "h2" : styleH2]) let a2: AttributedString = "Hello

world

,

welcome here

".set(style: StyleXML) // Apply a style defined via closure to a portion of the string let a3 = "Hello Guys!".set(Style({ $0.font = SystemFonts.Helvetica_Bold.font(size: 20) }), range: NSMakeRange(0,4)) ``` -------------------------------- ### Fonts & Colors in Style Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Details on how to use `FontConvertible` and `ColorConvertible` protocols for setting fonts and colors within a `Style`, including string-based and enum-based approaches. ```APIDOC ## Fonts & Colors in `Style` All colors and fonts you can set for a `Style` are wrapped by `FontConvertible` and `ColorConvertible` protocols. ### Font Handling SwiftRichString implements these protocols for `UIFont`/`NSFont` and `String`. You can assign a font by providing its PostScript name, which will be automatically translated to a valid instance. ```swift let firaLight: UIFont = "FiraCode-Light".font(ofSize: 14) let style = Style { $0.font = "Jura-Bold" $0.size = 24 } ``` On UIKit, `SystemFonts` enum provides a type-safe way to pick from available iOS fonts: ```swift let font1 = SystemFonts.Helvetica_Light.font(size: 15) let font2 = SystemFonts.Avenir_Black.font(size: 24) ``` ### Color Handling You can create valid color instances from HEX strings: ```swift let color: UIColor = "#0433FF".color let style = Style { $0.color = "#0433FF" } ``` Instances of colors and fonts can also be passed directly. ``` -------------------------------- ### Integrate Styles in Interface Builder and Programmatically Source: https://context7.com/malcommac/swiftrichstring/llms.txt Apply styles to UI components using the styleName property or by assigning a Style instance directly. ```swift // In Interface Builder: Set "styleName" inspectable property to "body" // Or programmatically class ViewController: UIViewController { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var bodyTextView: UITextView! @IBOutlet weak var inputField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Set style by name (must be registered in StylesManager) titleLabel.styleName = "heading" bodyTextView.styleName = "body" inputField.styleName = "input" // Or set style instance directly titleLabel.style = Style { $0.font = SystemFonts.Helvetica_Bold.font(size: 24) $0.color = UIColor.label } // Update text using styledText (automatically applies current style) titleLabel.styledText = "Welcome" bodyTextView.styledText = "This text is automatically styled." } } ``` -------------------------------- ### Configuring Dynamic Type Support for Styles Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Implement dynamic text scaling for fonts based on user preferences by configuring the `dynamicText` property within a Style. This uses UIFontMetrics properties wrapped in the DynamicText class. ```swift let style = Style { $0.font = UIFont.boldSystemFont(ofSize: 16.0) $0.dynamicText = DynamicText { $0.style = .body $0.maximumSize = 35.0 $0.traitCollection = UITraitCollection(userInterfaceIdiom: .phone) } } ``` -------------------------------- ### Apply styles with StyleRegEx Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Define styles that are applied automatically when a regular expression matches content within a string. ```swift let emailPattern = "([A-Za-z0-9_\-\.\+])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]+)" let style = StyleRegEx(pattern: emailPattern) { $0.color = UIColor.red $0.backColor = UIColor.yellow } let attrString = "My email is hello@danielemargutti.com and my website is http://www.danielemargutti.com".(style: style!) ``` -------------------------------- ### Derive New Styles with byAdding Source: https://context7.com/malcommac/swiftrichstring/llms.txt Use the `byAdding` method to create new style variants by extending or overriding attributes of an existing style without modifying the original. ```swift let baseStyle = Style { $0.font = SystemFonts.Helvetica_Light.font(size: 15) $0.color = UIColor.darkText $0.alignment = .left } // Derive a bold variant let boldStyle = baseStyle.byAdding { $0.font = SystemFonts.Helvetica_Bold.font(size: 15) } // Derive a highlighted variant let highlightedStyle = baseStyle.byAdding { $0.color = UIColor.white $0.backColor = UIColor.systemBlue } // Derive with trait variants let italicStyle = baseStyle.byAdding { $0.traitVariants = .italic } // Chain derivations let boldItalicStyle = boldStyle.byAdding { $0.traitVariants = .italic } let normalText = "Normal text".set(style: baseStyle) let boldText = "Bold text".set(style: boldStyle) let highlightedText = "Highlighted text".set(style: highlightedStyle) ``` -------------------------------- ### StyleRegEx: Apply styles via regular expressions Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md StyleRegEx enables applying styles to strings by matching regular expressions. This is useful for dynamically styling patterns like email addresses or URLs. ```APIDOC ## StyleRegEx: Apply styles via regular expressions ### Description StyleRegEx allows you to define a style that is applied when a specific regular expression pattern is matched within the target string or attributed string. ### Usage ```swift let emailPattern = "([A-Za-z0-9_\-\.\+])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]+)" let style = StyleRegEx(pattern: emailPattern) { $0.color = UIColor.red $0.backColor = UIColor.yellow } let attrString = "My email is hello@danielemargutti.com and my website is http://www.danielemargutti.com".set(style: style!) ``` ### Parameters - `pattern` (String) - The regular expression pattern to match. - `configuration` ( (Style) -> Void ) - A closure to configure the style applied to matched text. ``` -------------------------------- ### Apply Deferred Style by Name Source: https://context7.com/malcommac/swiftrichstring/llms.txt Apply a style that is created on demand via the deferred style provider. The style is looked up by its string name. ```swift let errorText = "An error occurred".set(style: "error") ``` -------------------------------- ### Deriving a New Style with Modifications Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Create a new style based on an existing one using the `byAdding()` function. This allows for inheriting attributes and overriding or adding new ones. ```swift let initialStyle = Style { $0.font = SystemFonts.Helvetica_Light.font(size: 15) $0.alignment = right } // The following style contains all the attributes of initialStyle // but also override the alignment and add a different foreground color. let subStyle = bold.byAdding { $0.alignment = center $0.color = UIColor.red } ``` -------------------------------- ### Defer Style Creation on Demand Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Implement the `onDeferStyle()` callback in `StylesManager` to create styles on demand. This method receives the style's identifier and can return a style instance and a boolean indicating whether to cache it. ```swift Styles.onDeferStyle = { name in if name == "MyStyle" { let normal = Style { $0.font = SystemFonts.Helvetica_Light.font(size: 15) } let bold = Style { $0.font = SystemFonts.Helvetica_Bold.font(size: 20) $0.color = UIColor.red $0.backColor = UIColor.yellow } let italic = normal.byAdding { $0.traitVariants = .italic } return (StyleXML(base: normal, ["bold": bold, "italic": italic]), true) } return (nil,false) } ``` -------------------------------- ### Apply Shadows and Strokes to Text Source: https://context7.com/malcommac/swiftrichstring/llms.txt Define shadow effects and stroke outlines using Style objects. ```swift // Shadow effect let shadowStyle = Style { $0.font = SystemFonts.Helvetica_Bold.font(size: 24) $0.color = UIColor.white let shadow = NSShadow() shadow.shadowColor = UIColor.black.withAlphaComponent(0.5) shadow.shadowOffset = CGSize(width: 2, height: 2) shadow.shadowBlurRadius = 4 $0.shadow = shadow } // Stroke (outline) effect let outlineStyle = Style { $0.font = SystemFonts.Helvetica_Bold.font(size: 32) $0.stroke = (UIColor.black, -3.0) // Negative width = stroke + fill $0.color = UIColor.yellow } // Stroke only (no fill) let strokeOnlyStyle = Style { $0.font = SystemFonts.Helvetica_Bold.font(size: 32) $0.stroke = (UIColor.blue, 2.0) // Positive width = stroke only } let shadowedText = "Shadow Text".set(style: shadowStyle) let outlinedText = "OUTLINED".set(style: outlineStyle) ``` -------------------------------- ### Apply Styles with Regular Expressions using StyleRegEx Source: https://context7.com/malcommac/swiftrichstring/llms.txt Use `StyleRegEx` to apply styles to text that matches specific regular expression patterns, such as emails, URLs, or hashtags. This enables targeted styling of dynamic content. ```swift // Style for email addresses let emailPattern = "([A-Za-z0-9_\-\.\+])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]+)" let emailStyle = StyleRegEx(pattern: emailPattern) { $0.color = UIColor.systemBlue $0.underline = (.single, UIColor.systemBlue) } // Style for hashtags let hashtagPattern = "#[A-Za-z0-9_]+" let hashtagStyle = StyleRegEx(pattern: hashtagPattern) { $0.color = UIColor.systemPurple $0.font = SystemFonts.Helvetica_Bold.font(size: 14) } // Style for @mentions let mentionPattern = "@[A-Za-z0-9_]+" let mentionStyle = StyleRegEx(pattern: mentionPattern) { $0.color = UIColor.systemOrange } // Apply regex style to text let socialText = "Contact me at hello@example.com or @username. Check out #SwiftRichString!" if let styledEmail = emailStyle?.set(to: socialText, range: nil) { myLabel.attributedText = styledEmail } // Combine with base style let baseStyle = Style { $0.font = SystemFonts.Helvetica.font(size: 14) $0.color = UIColor.darkText } let regexWithBase = StyleRegEx(base: baseStyle, pattern: emailPattern) { $0.color = UIColor.systemBlue } ``` -------------------------------- ### Render XML String with Styles Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Apply a StyleXML instance to an XML-tagged string to render it as an NSAttributedString. This is useful for displaying dynamic content with rich text formatting. ```swift let bodyHTML = "Hello world!, my name is Daniele" self.textView?.attributedText = bodyHTML.set(style: group) ``` -------------------------------- ### Define Styles for XML Rendering Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Define base, bold, and italic styles for rendering XML/HTML tagged strings. Ensure styles are correctly configured for font, line spacing, kerning, and dynamic text properties. ```swift let baseStyle = Style { $0.font = UIFont.boldSystemFont(ofSize: self.baseFontSize * 1.15) $0.lineSpacing = 1 $0.kerning = Kerning.adobe(-20) } let boldStyle = Style { $0.font = UIFont.boldSystemFont(ofSize: self.baseFontSize) $0.dynamicText = DynamicText { $0.style = .body $0.maximumSize = 35.0 $0.traitCollection = UITraitCollection(userInterfaceIdiom: .phone) } } let italicStyle = Style { $0.font = UIFont.italicSystemFont(ofSize: self.baseFontSize) } ``` ```swift let groupStyle = StyleXML.init(base: baseStyle, ["b" : boldStyle, "i": italicStyle]) ``` -------------------------------- ### Add Clickable Links to Text Source: https://context7.com/malcommac/swiftrichstring/llms.txt Shows how to add clickable links to attributed strings using the `linkURL` property within a `Style`. Also demonstrates integration with `UITextView` and parsing links from HTML-like strings. ```swift let linkStyle = Style { $0.font = SystemFonts.Helvetica.font(size: 16) $0.color = UIColor.systemBlue $0.underline = (.single, UIColor.systemBlue) $0.linkURL = URL(string: "https://github.com/malcommac/SwiftRichString") } let textWithLink = "Visit SwiftRichString on GitHub".set(style: linkStyle) // Using in a UITextView (must enable link interaction) let textView = UITextView() textView.attributedText = textWithLink textView.isEditable = false textView.isSelectable = true textView.dataDetectorTypes = .link // Links in XML using StandardXMLAttributesResolver (default) let htmlLink = "Click here to visit." let linkGroup = StyleXML(base: bodyStyle, [ "a": Style { $0.color = UIColor.systemBlue $0.underline = (.single, nil) } ]) // StandardXMLAttributesResolver automatically handles href attribute let renderedLink = htmlLink.set(style: linkGroup) ``` -------------------------------- ### Interface Builder Styling Properties Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md SwiftRichString extends `UILabel`, `UITextView`, and `UITextField` with properties to enable styling directly from Interface Builder. ```APIDOC ## Interface Builder Styling Properties SwiftRichString provides the following properties for `UILabel`, `UITextView`, and `UITextField` when used with Interface Builder: ### Properties - **styleName** (String): Available via IB. Set this to render the text already set via Interface Builder with a globally registered style before the parent view of the UI control is loaded. - **style** (StyleProtocol): Set this to render the text of the control with an instance of a style. - **styledText** (String): Use this property instead of `attributedText` to set new text for the control and render it with an already set style. You can continue to use `attributedText` and set the value using `.set()` functions of `String`/`AttributedString`. ### Style Types Assigned style can be a `Style`, `StyleXML`, or `StyleRegEx`: - If the style is a `Style`, the entire text of the control is set with the attributes defined by the style. - If the style is a `StyleXML`, a base attribute is set (if `base` is valid) and other attributes are applied once each tag is found. - If the style is a `StyleRegEx`, a base attribute is set (if `base` is valid) and the attribute is applied only for matches of the specified pattern. ### Usage Examples Typically, you will set the style of a label via the `Style Name` (`styleName`) property in IB and update the content of the control by setting the `styledText`: ```swift // Use `styleName` set value to update a text with the style self.label?.styledText = "Another text to render" // text is rendered using specified `styleName` value. ``` Alternatively, you can set values manually: ```swift // Manually set an attributed string self.label?.attributedText = (self.label?.text ?? "").set(myStyle) // Manually set the style via instance self.label?.style = myStyle self.label?.styledText = "Updated text" ``` ``` -------------------------------- ### Creating Color from HEX String Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Create a UIColor instance directly from a HEX color string. This is a convenient way to define colors for styles. ```swift let color: UIColor = "#0433FF".color ``` ```swift let style = Style { $0.color = "#0433FF" ... } ``` -------------------------------- ### Render XML/HTML Tags with StyleXML Source: https://context7.com/malcommac/swiftrichstring/llms.txt Utilize `StyleXML` (or `StyleGroup`) to render strings containing XML/HTML tags by mapping tags to predefined style definitions. Ensure individual styles are defined before creating the `StyleXML` group. ```swift // Define individual styles let baseStyle = Style { $0.font = SystemFonts.Helvetica_Light.font(size: 15) $0.color = UIColor.darkText } let boldStyle = Style { $0.font = SystemFonts.Helvetica_Bold.font(size: 15) $0.color = UIColor.black } let italicStyle = Style { $0.font = SystemFonts.Helvetica_LightOblique.font(size: 15) } let linkStyle = Style { $0.color = UIColor.systemBlue $0.underline = (.single, UIColor.systemBlue) } // Create a StyleXML group let htmlGroup = StyleXML(base: baseStyle, [ "b": boldStyle, "strong": boldStyle, "i": italicStyle, "em": italicStyle, "a": linkStyle ]) // Render tagged string let taggedString = "Hello World! This is SwiftRichString. Visit our website." let renderedText = taggedString.set(style: htmlGroup) myTextView.attributedText = renderedText ``` -------------------------------- ### Setting Font by PostScript Name Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Assign a font to a Style by providing its PostScript name as a string. The font will be automatically translated to a valid UIFont instance. ```swift let firaLight: UIFont = "FiraCode-Light".font(ofSize: 14) ``` ```swift let style = Style { $0.font = "Jura-Bold" $0.size = 24 ... } ``` -------------------------------- ### Style Class Properties Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md A comprehensive list of properties available in the Style class for configuring attributed strings. ```APIDOC ## Style Class Properties ### Description The Style class provides a set of properties to define text attributes such as font, color, paragraph spacing, and alignment for attributed strings. ### Properties - **size** (CGFloat) - font size in points - **font** (FontConvertible) - font used in text - **color** (ColorConvertible) - foreground color of the text - **backColor** (ColorConvertible) - background color of the text - **shadow** (NSShadow) - shadow effect of the text - **underline** ((NSUnderlineStyle?, ColorConvertible?)) - underline style and color - **strikethrough** ((NSUnderlineStyle?, ColorConvertible?)) - strikethrough style and color - **baselineOffset** (Float) - character’s offset from the baseline, in points - **paragraph** (NSMutableParagraphStyle) - paragraph attributes - **lineSpacing** (CGFloat) - distance in points between lines - **paragraphSpacingBefore** (CGFloat) - distance between the paragraph’s top and text content - **paragraphSpacingAfter** (CGFloat) - space added at the end of the paragraph - **alignment** (NSTextAlignment) - text alignment of the receiver - **firstLineHeadIndent** (CGFloat) - distance from leading margin to the first line - **headIndent** (CGFloat) - distance from leading margin to lines other than the first - **tailIndent** (CGFloat) - distance from the leading or trailing margin - **lineBreakMode** (LineBreak) - mode used to break lines - **minimumLineHeight** (CGFloat) - minimum height in points for any line - **maximumLineHeight** (CGFloat) - maximum height in points for any line - **baseWritingDirection** (NSWritingDirection) - initial writing direction ``` -------------------------------- ### Lazy Image Loading with Custom Image Provider Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Implement a custom `imageProvider` callback in `StyleXML` to lazily load images. This method is invoked when an `img` tag is encountered, allowing you to return a custom image or `nil` to use default asset loading. ```swift let xmlText = "- has done!" let xmlStyle = StyleXML(base: { /// some attributes for base style }) // This method is called when a new `img` tag is found. It's your chance to // return a custom image. If you return `nil` (or you don't implement this method) // image is searched inside any bundled `xcasset` file. xmlStyle.imageProvider = { (imageName, attributes) in sswitch imageName { case "check": // create & return your own image default: // ... } } self.textView?.attributedText = xmlText.set(style: x) ``` -------------------------------- ### Register Global Styles with StyleNames Struct Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Define a non-instantiable struct to hold style identifiers for type-safe global style registration. Register styles using `Styles.register()` with a unique identifier. ```swift // Define a struct with your styles names public struct StyleNames { public static let body: String = "body" hpublic static let h1: String = "h1" public static let h2: String = "h2" private init() { } } ``` ```swift let bodyStyle: Style = ... Styles.register(StyleNames.body, bodyStyle) ``` ```swift let text = "hello world".set(StyleNames.body) ``` -------------------------------- ### Add, Set, and Remove Attributes on Attributed Strings Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Demonstrates chaining methods to add, set, and remove styles from attributed strings. Chaining is allowed as these methods return the receiver instance. ```swift let a = "hello".set(style: styleA) let b = "world!".set(style: styleB) let ab = (a + b).add(styles: [coupondStyleA,coupondStyleB]).remove([.foregroundColor,.font]) ``` -------------------------------- ### Implement XMLDynamicAttributesResolver for custom attributes Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Define a custom resolver to handle attributes like color within known XML tags. ```swift // First define our own resolver for attributes open class MyXMLDynamicAttributesResolver: XMLDynamicAttributesResolver { public func applyDynamicAttributes(to attributedString: inout AttributedString, xmlStyle: XMLDynamicStyle) { let finalStyleToApply = Style() xmlStyle.enumerateAttributes { key, value in switch key { case "color": // color support finalStyleToApply.color = Color(hexString: value) default: break } } attributedString.add(style: finalStyleToApply) } } // Then set it to our's StyleXML instance before rendering text. let groupStyle = StyleXML.init(base: baseStyle, ["b" : boldStyle, "i": italicStyle]) groupStyle.xmlAttributesResolver = MyXMLDynamicAttributesResolver() ``` -------------------------------- ### Update text using styleName Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Updates the control text using a pre-registered style name set in Interface Builder. ```swift // use `styleName` set value to update a text with the style self.label?.styledText = "Another text to render" // text is rendered using specified `styleName` value. ``` -------------------------------- ### Compose strings with function builders Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Use AttributedString.composing to build attributed strings using a declarative syntax. ```swift let bold = Style { ... } let italic = Style { ... } let attributedString = AttributedString.composing { "hello".set(style: bold) "world".set(style: italic) } ``` -------------------------------- ### Modify Attributed Strings Source: https://context7.com/malcommac/swiftrichstring/llms.txt Demonstrates adding, setting, and removing styles from existing attributed strings using various methods like `add`, `set`, and `removeAttributes`. ```swift let initialText = "Hello World".set(style: Style { $0.font = SystemFonts.Helvetica.font(size: 16) $0.color = UIColor.black }) // Add additional attributes (merge with existing) let highlightStyle = Style { $0.backColor = UIColor.yellow } initialText.add(style: highlightStyle, range: NSRange(location: 6, length: 5)) // Replace attributes in range let boldStyle = Style { $0.font = SystemFonts.Helvetica_Bold.font(size: 16) } initialText.set(style: boldStyle, range: NSRange(location: 0, length: 5)) // Remove specific attributes initialText.removeAttributes([.backgroundColor], range: NSRange(location: 6, length: 5)) // Remove all attributes defined by a style initialText.remove(highlightStyle) // Chain operations let chainedResult = "Chained Operations" .set(style: bodyStyle) .add(style: boldStyle, range: NSRange(location: 0, length: 7)) .add(style: highlightStyle, range: NSRange(location: 8, length: 10)) myLabel.attributedText = chainedResult ``` -------------------------------- ### Compose Attributed Strings with Function Builder Source: https://context7.com/malcommac/swiftrichstring/llms.txt Utilize Swift's function builder syntax for declarative composition of attributed strings. This allows for a clean, readable way to combine different styles. ```swift let titleStyle = Style { $0.font = SystemFonts.Helvetica_Bold.font(size: 20) $0.color = UIColor.black } let bodyStyle = Style { $0.font = SystemFonts.Helvetica.font(size: 14) $0.color = UIColor.darkGray } let highlightStyle = Style { $0.font = SystemFonts.Helvetica_Bold.font(size: 14) $0.color = UIColor.systemBlue } let composedText = AttributedString.composing { "Welcome\n".set(style: titleStyle) "This is a ".set(style: bodyStyle) "highlighted".set(style: highlightStyle) " section of text.".set(style: bodyStyle) } ``` -------------------------------- ### Apply Multiple Text Transforms in Order Source: https://context7.com/malcommac/swiftrichstring/llms.txt Combine multiple text transforms in the `textTransforms` array. They are applied sequentially in the order they appear. ```swift let multiTransformStyle = Style { $0.font = SystemFonts.Helvetica.font(size: 14) $0.textTransforms = [ .capitalized, .custom { $0.trimmingCharacters(in: .whitespaces) } ] } ``` -------------------------------- ### Concatenate strings and styles Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Use the + operator to combine strings, attributed strings, and styles. ```swift let body: Style = Style { ... } let big: Style = Style { ... } let attributed: AttributedString = "hello ".set(style: body) // the following code produce an attributed string by // concatenating an attributed string and two plain string // (one styled and another plain). let attStr = attributed + "\(username)!".set(style:big) + ". You are welcome!" ``` ```swift // This produce an attributed string concatenating a plain // string with an attributed string created via + operator // between a plain string and a style let attStr = "Hello" + ("\(username)" + big) ``` -------------------------------- ### Create Attributed String with Local Image Source: https://github.com/malcommac/swiftrichstring/blob/master/README.md Construct an attributed string with a local image, specifying its bounds for size and vertical alignment relative to the text baseline. ```swift let localTextAndImage = AttributedString(image: UIImage(named: "rocket")!, bounds: CGRect(x: 0, y: -20, width: 25, height: 25)) ```