SwiftRichString:几乎富文本字符串的一切都在这个库中找到

baiyu 8年前
   <p style="text-align:center"><img src="https://simg.open-open.com/show/1c83703c4ec652b924819f4f4962ca00.png"></p>    <h2>SwiftRichString</h2>    <p>SwiftRichString is a lightweight library wich allows you to simplify your work with attributed strings in UIKit. It provides convenient way to create and manage string with complex attributes, render tag-based string and manipulate styles at specified indexes. Currently it's compatible with iOS and tvOS.</p>    <p>And, best of all, it's fully compatible with unicode (who don't love emoji?).</p>    <p>★★ <strong>Star our github repository to help us!</strong> ★★</p>    <h2>You also may like</h2>    <p>Do you like SwiftRichString ? I'm also working on several other opensource libraries.</p>    <p>Take a look here:</p>    <ul>     <li><strong><a href="/misc/goto?guid=4958875017227447251" rel="nofollow,noindex">SwiftDate</a> </strong> - Full features Dates & TimeZone management for iOS,macOS,tvOS and watchOS</li>     <li><strong><a href="/misc/goto?guid=4959730447485913988" rel="nofollow,noindex">SwiftLocation</a> </strong> - CoreLocation and Beacon Monitoring on steroid!</li>     <li><strong><a href="/misc/goto?guid=4959730447590814014" rel="nofollow,noindex">SwiftScanner</a> </strong> - String scanner in pure Swift with full unicode support</li>     <li><strong><a href="/misc/goto?guid=4959730447676042128" rel="nofollow,noindex">SwiftSimplify</a> </strong> - Tiny high-performance Swift Polyline Simplification Library</li>    </ul>    <h2>On Medium</h2>    <p>I've just wrote an article which cover the basic concepts of SwiftRichString. You can found it on Medium at <a href="/misc/goto?guid=4959730447758869266" rel="nofollow,noindex">Attributed String in Swift: the right way</a> .</p>    <h2>Documentation</h2>    <ul>     <li><strong>Introduction </strong></li>     <li><strong>Playground </strong></li>     <li><strong>Define your own Style </strong></li>     <li><strong>Apply style to a String </strong></li>     <li><strong>Apply style on substring with Range </strong></li>     <li>Apply style/s on substring with NSRegularExpression</li>     <li><strong>Combine Strings and Attributed Strings </strong></li>     <li><strong>Create tagged strings </strong></li>     <li><strong>Parse and render tag-based content </strong></li>     <li><strong>Available text attributes in Style </strong></li>     <li><strong>API Documentation </strong></li>    </ul>    <h2>Other Infos</h2>    <ul>     <li><strong>Installation (via CocoaPods, Carthage or Swift PM) </strong></li>     <li><strong>Credits & License </strong></li>    </ul>    <h2>Documentation</h2>    <h2>Introduction</h2>    <p>SwiftRichString integrate seamlessy into UIKit/AppKit by allowing you to manage, combine and apply styles directly on NSMutableAttributedString instances. This library define only two main entities:</p>    <ul>     <li> <p>Style is the central point of SwiftRichString : this class allows you to create easily and safety a collection of styles (align, text color, ligature, font etc.). In fact the ideal use-case is to create your own set of styles for your app, then apply to your strings.</p> </li>     <li> <p>MarkupString allows you to load a string which is pretty like a web page where your content can contain styles enclosed between classic html-style tags ( ie. "<bold>Hello</bold> <nameStyle>\(username)</nameStyle> ). MarkupString will parse data for your by generating a valid NSMutableAttributedString along your choosed Styles .</p> </li>     <li> <p>Also there are several NSMutableAttributedString and String extensions allows you to play and combine strings and styles easily without introducing extra structures to your code and by mantaing readability.</p> </li>    </ul>    <h2>Playground</h2>    <p>If you want to play with SwiftRichString we have also made a small Playground. Take a look at Playground.playground file inside the SwiftRichString.xcworkspace .</p>    <h2>Define your own Style</h2>    <p>Style is a class which define attributes you can apply to strings in a type-safe swifty way. Each style has a name and a set of attributes you can set.</p>    <p>Creating Style is pretty easy. In this example we create a style which set a particular font with given size and color.</p>    <pre>  <code class="language-swift">let big = Style("italic", {    $0.font = FontAttribute(.CourierNewPS_ItalicMT, size: 25)    $0.color = UIColor.red  })</code></pre>    <p>This is also a special style called .default . Default - if present - is applied automatically before any other style to the entire sender string. Other styles are applied in order just after it.</p>    <pre>  <code class="language-swift">let def = Style.default {    $0.font = FontAttribute(.GillSans_Italic, size: 20)  }</code></pre>    <h2>Apply Style to String</h2>    <p>Styles can be applied directly to String instances (by generating NSMutableAttributedString automatically) or on existing NSMutableAttributedString .</p>    <p>In this example we can combine simple String instances and apply your own set of styles:</p>    <pre>  <code class="language-swift">// Define your own used styles  let bold = Style("bold", {    $0.font = FontAttribute(.CourierNewPS_BoldItalicMT, size: 30) // font + size    $0.color = UIColor.red // text color     $0.align = .center // align on center  })    let italic = Style("italic", {    $0.font = FontAttribute(.CourierNewPS_ItalicMT, size: 25)    $0.color = UIColor.green  })    let attributedString = ("Hello " + userName).set(style: bold) + "\nwelcome here".set(style: italic)</code></pre>    <p>Will produce:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/e22ce9b18bcbb23228046377deb7d64b.png"></p>    <h2>Apply style on substring with Range</h2>    <p>You can also apply one or more styles to a substring by passing a valid range. In this example we want to apply bold style to the "Man!" substring.</p>    <pre>  <code class="language-swift">let style_bold = Style("bold", {    $0.font = FontAttribute(.Futura_CondensedExtraBold, size: 20)  })  let renderText = "Hello Man! Welcome".set(style: style_bold, range: 6..<10)</code></pre>    <p>Will produce:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/114a57b220a81102e4e0753d3ce9400b.png"></p>    <h2>Apply style/s on substring with NSRegularExpression</h2>    <p>Regular expressions are also supported; you can add your own style/s to matched strings. SwiftRichString has fully unicode support.</p>    <pre>  <code class="language-swift">let sourceText = ":imp:��the winner"  let attributedString = sourceText.set(styles: myStyle, pattern: "the winner", options: .caseInsensitive)    // another example  let sourceText = "prefix12 aaa3 prefix45"  let attributedText = sourceText.set(styles: myStyle, pattern: "fix([0-9])([0-9])", options: .caseInsensitive)</code></pre>    <p>Will produce:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/6ce109831945ca3783b1e95cd8cbe10b.png"></p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/4535abd533035d3ce1ac81a4b14a8b42.png"></p>    <h2>Combine Strings and Attributed Strings</h2>    <p>You can combine String and NSMutableAttributedString easily with + operator.</p>    <p>For example:</p>    <pre>  <code class="language-swift">let part1 = "Hello"  let part2 = "Mario"  let part3 = "Welcome here!"    // You can combine simple String and `NSMutableAttributedString`  // Resulting is an `NSMutableAttributedString` instance.  let result = part1 + " " + part2.set(style: bold) + " " + part3</code></pre>    <p>You can avoid creating new instances of NSMutableAttributedString and change directly your instance:</p>    <pre>  <code class="language-swift">let attributedText = "Welcome".set(style: bold)  // Render a simple string with given style and happend it to the previous instance  attributedText.append(string: " mario! ", style: bold)</code></pre>    <p>Is possible to append a MarkupString to an NSMutableAttributedString instance:</p>    <pre>  <code class="language-swift">let sourceURL = URL(fileURLWithPath: "...")  let markUpObj = RichString(sourceURL, encoding: .utf8, [bold,italic])!    let finalAttributed = "Welcome!".set(style: bold)  // Create an `NSMutableAttributedString` render from markUpObj and append it to the instance  finalAttributed.append(markup: markUpObj)</code></pre>    <h2>Create tagged strings</h2>    <p>Sometimes you may have a text you want to render with your own favorite application's styles, like HTML/CSS does with web page. With SwiftRichString it's really easy; add your favourite tags to your source string, create associated Style and apply them. Let me show an example:</p>    <pre>  <code class="language-swift">// First of all we want to define all `Style` you want to use in your  // source string.  // Each style has its own name (any letter-based identifier) you should use in your source string  let tStyle1 = Style("style1", {    $0.font = FontAttribute(.AvenirNextCondensed_Medium, size: 50)    $0.color = UIColor.red  })    let tStyle2 = Style("style2", {    $0.font = FontAttribute(.HelveticaNeue_LightItalic, size: 20)    $0.color = UIColor.green    $0.backColor = UIColor.yellow  })    // Create and render text  let text = "Hello <style1>\(userName)!</style1>, <style2>welcome here!</style2>"  let renderedText = text.parse(tStyle1,tStyle2).text</code></pre>    <h2>Parse and render tag-based content</h2>    <p>MarkupString allows you to load an tags-based string (even from a file, a literals or content from url) and parse it by applying with your own styles.</p>    <p>Suppose you have this text:</p>    <pre>  <code class="language-swift"><center>The quick brown fox</center>\njumps over the lazy dogis an <italic>English-language</italic> pangram—a phrase that contains <italic>all</italic> of the letters of the alphabet. It is <extreme><bold>commonly</bold></extreme> used for touch-typing practice.</code></pre>    <p>This text defines following styles: "center", "bold", "italic" and "extreme" .</p>    <p>So, in order to render your text you may want create Style instances which represent these tags:</p>    <pre>  <code class="language-swift">let style_bold = Style("bold", {    $0.font = FontAttribute(.Futura_CondensedExtraBold, size: 15)  })    let style_center = Style("center", {    $0.font = FontAttribute(.Menlo_Regular, size: 15)    $0.align = .center  })    let style_italic = Style("italic", {    $0.font = FontAttribute(.HelveticaNeue_LightItalic, size: 15)    $0.color = UIColor.red  })    let style_exteme = Style("extreme", {    $0.font = FontAttribute(.TimesNewRomanPS_BoldItalicMT, size: 40)    $0.underline = UnderlineAttribute(color: UIColor.blue, style: NSUnderlineStyle.styleSingle)  })    let sourceTaggedString = "<center>The quick brown fox ...  let parser = try! MarkupString(source: sourceTaggedString, [style_center,style_italic,style_exteme,style_bold])  // Render attributes string  // Result is parsed only upon requested, only first time (then it will be cached).  let test_7 = parser.render(withStyles: [style_bold,style_center,style_italic,style_exteme])</code></pre>    <p>Will produce:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/a852360787971df6f141f83ab6d6f039.png"></p>    <p>Clearly you can load string also from file at specified URL :</p>    <pre>  <code class="language-swift">let sourceURL = URL(fileURLWithPath: "...")  let renderedText = RichString(sourceURL, encoding: .utf8, [bold,italic])!.text</code></pre>    <h2>API Documentation</h2>    <h3>Create NSMutableAttributedString from String</h3>    <p>func set(style: Style, range: Range<Int>? = nil) -> NSMutableAttributedString Create an NSMutableAttributedString from a simple String instance by applying given style at specified range. If range is missing style will be applied to the entire string.</p>    <p>func set(styles: Style...) -> NSMutableAttributedString Create an NSMutableAttributedString from a simple String instance by applying given styles . Styles are applied in sequence as passed; the only exception is the .default Style if present; in this case .default style is applied in first place.</p>    <p>func set(styles: Style..., pattern: String, options: NSRegularExpression.Options = .caseInsensitive) -> NSAttributedString Create an NSMutableAttributedString from a simple String instance by applying given styles with specified regular expression pattern. Styles are applied in sequence as passed; the only exception is the .default Style if present; in this case .default style is applied in first place.</p>    <h3>Manage NSMutableAttributedString</h3>    <p>func append(string: String, style: Style) Append a String instance to an existing NSMutableAttributedString by applying given style .</p>    <p>func append(markup string: MarkupString, styles: Style...) Append a MarkupString instance to an existing NSMutableAttributedString by applying given styles .</p>    <p>func add(style: Style, range: Range<Int>? = nil) -> NSMutableAttributedString Append attributes defined by style at given range of existing NSMutableAttributedString Return self for chain purpose.</p>    <p>func add(styles: Style...) -> NSMutableAttributedString Append attributes defined by passed styles into current NSMutableAttributedString . Return self for chain purpose.</p>    <p>func set(style: Style, range: Range<Int>? = nil) -> NSMutableAttributedString Replace any exiting attribute into given range with the one passed in style . Return self for chain purpose.</p>    <p>func set(styles: Style...) -> NSMutableAttributedString Replace any existing attribute into current instance of the attributed string with styles passed. Styles are applied in sequence as passed; the only exception is the .default Style if present; in this case .default style is applied in first place. Return self for chain purpose.</p>    <p>func remove(style: Style, range: Range<Int>? = nil) -> NSMutableAttributedString Remove attributes keys defined in passed style from the instance.</p>    <h3>Combine String and NSMutableAttributedString</h3>    <p>Combine between simple String and NSMutableAttributedString is pretty straightforward using the Swift's standard + operator. Just an example:</p>    <pre>  <code class="language-swift">var test_1 = "Hello".set(style: bold) + "\n" + "World!".set(style: highlighted)  test_1.append(string: "\nHow old are you?", style: monospaced)</code></pre>    <h2>Available Text Attributes</h2>    <p>You can define your text attributes in type-safe Swift way. This is the list of attributes you can customize:</p>    <table cellspacing="0">     <tbody>      <tr>       <td>PROPERTY</td>       <td>DESCRIPTION</td>       <td>ATTRIBUTES</td>      </tr>      <tr>       <td>`.align`</td>       <td>Text alignment</td>       <td>Any value of NSTextAlignment.<br> <br> Example = `$0.align = .center`</td>      </tr>      <tr>       <td>`.lineBreak`</td>       <td>The mode that should be used to break lines</td>       <td>Any value of NSLineBreakMode.<br> <br> Example = `$0.lineBreak = .byWordWrapping`</td>      </tr>      <tr>       <td>`.paragraphSpacing`</td>       <td>The space after the end of the paragraph.</td>       <td>`Float`<br> Example:<br> * `$0.paragraphSpacing = 4`<br> <br> Space measured in pointsadded at the end of the paragraph to separate it from the following paragraph.<br> Always nonnegative. The space between paragraphs is determined by adding the previous paragraph�s paragraphSpacing.</td>      </tr>      <tr>       <td>`.font`</td>       <td>Font & Font size to apply</td>       <td>FontAttribute<br> <br> FontAttribute is an helper enum which allows you to define in type safe Swift way font attributes.<br> All system fonts are listed; you can however load a custom font from a string (classic mode) or extended FontAttribute enum to add your own custom font.<br> <br> Example:<br> * `$0.font = FontAttribute(.CourierNewPS_BoldItalicMT, size: 30)` (from enum)<br> * `$0.font = FontAttribute("MyCustomFontFamilyName", size: 40` (from raw string)</td>      </tr>      <tr>       <td>`.color`</td>       <td>Text color</td>       <td>Any valid UIColor instance. `SwiftRichString` also accepts UIColor from HEX string (like "#FF4555")<br> <br> Example:<br> * `$0.color = UIColor.red`<br> * `$0.color = UIColor(hex: "#FF4555")</td>      </tr>      <tr>       <td>`.backColor`</td>       <td>Background text color</td>       <td>Same of `.color`</td>      </tr>      <tr>       <td>`.stroke`</td>       <td>Stroke attributes of text</td>       <td>`StrokeAttribute`<br> <br> `StrokeAttribute` is an helper class which also allows you to define a stroke's `.color` and `.width`.<br> * `.color` (`UIColor`) color of the stroke;  if not defined it is assumed to be the same as the value of color; otherwise, it describes the outline color.<br> * `.width` (`CGFloat`) Amount to change the stroke width and is specified as a percentage of the font point size. Specify 0 (the default) for no additional changes.</td>      </tr>      <tr>       <td>`.underline`</td>       <td>Underline attributes of text</td>       <td>`UnderlineAttribute`<br> <br> `UnderlineAttribute` is an helper struct which allows you to define `.color` and `.style` of the underline attribute.<br> * `.color` (`UIColor`) Underline color, if missing  same as foreground color.<br> * `.style` (`NSUnderlineStyle`) The style of the underline, by default is `.styleNone`</td>      </tr>      <tr>       <td>`.strike`</td>       <td>Strike attributes of text</td>       <td>`StrikeAttribute`<br> <br> `StrikeAttribute` is an helper struct which allows you to define strike attributes: `.color` and `.style`.<br> * `.color` (`UIColor`) Underline color, if missing  same as foreground color.<br> * `.style` (`NSUnderlineStyle`) This value indicates whether the text is underlined and corresponds to one of the constants described in NSUnderlineStyle.</td>      </tr>      <tr>       <td>`.shadow`</td>       <td>Shadow attributes of text (only for macOS and iOS)</td>       <td>`ShadowAttribute`<br> <br> `ShadowAttribute` defines following properties:<br> * `.offset` (`CGSize`) horizontal and vertical offset values, specified using the width and height fields of the CGSize data type.<br> * `.blurRadius` (`CGFloat`) This property contains the blur radius, as measured in the default user coordinate space. A value of 0 indicates no blur, while larger values produce correspondingly larger blurring. This value must not be negative. The default value is 0.<br> * `.color` (`UIColor`) The default shadow color is black with an alpha of 1/3. If you set this property to nil, the shadow is not drawn.</td>      </tr>      <tr>       <td>`.firstLineheadIntent`</td>       <td>The indentation of the first line.</td>       <td>`Float`<br> Example:<br> * `$0.firstLineHeadIntent = 0.5`<br> <br> The distance (in points) from the leading margin of a text container to the beginning of the paragraph�s first line.</td>      </tr>      <tr>       <td>`.headIndent`</td>       <td>The indentation of lines other than the first.</td>       <td>`Float`<br> Example:<br> * `$0.headIdent = 4`<br> <br> The distance (in points) from the leading margin of a text container to the beginning of lines other than the first. This value is always nonnegative.</td>      </tr>      <tr>       <td>`.tailIndent`</td>       <td>The trailing indentation.</td>       <td>`Float`<br> Example:<br> * `$0.tailIndent = 2`<br> <br> If positive, this value is the distance from the leading margin (for example, the left margin in left-to-right text).<br> If 0 or negative, it�s the distance from the trailing margin.</td>      </tr>      <tr>       <td>`.maximumLineHeight`</td>       <td>Maximum line height.</td>       <td>`Float`<br> Example:<br> * `$0.maximumLineHeight = 2`<br> <br> This property contains the maximum height in points that any line in the receiver will occupy, regardless of the font size or size ofany attached graphic. This value is always nonnegative. The default value is 0. Glyphs and graphics exceeding this height will overlap neighboring lines; however, a maximum height of 0 implies no line height limit.<br> Although this limit applies to the line itself, line spacing adds extra space between adjacent lines.</td>      </tr>      <tr>       <td>`.minimumLineHeight`</td>       <td>Minimum line height.</td>       <td>`Float`<br> Example:<br> * `$0.minimumLineHeight = 2`<br> <br> This property contains the minimum height in points that any line in the receiver will occupy, regardless of the font size or size of any attached graphic. This value is always nonnegative</td>      </tr>      <tr>       <td>`.lineSpacing`</td>       <td>Distance in points between the bottom of one line fragment and the top of the next.</td>       <td>`Float`<br> Example:<br> * `$0.lineSpacing = 1`<br> <br> The distance in points between the bottom of one line fragment and the top of the next.<br> This value is always nonnegative. This value is included in the line fragment heights in the layout manager.</td>      </tr>      <tr>       <td>`.paragraphSpacingBefore`</td>       <td>Distance between the paragraph�s top and the beginning of its text content.</td>       <td>`Float`<br> Example:<br> * `$0.paragraphSpacingBefore = 1`<br> <br> The space (measured in points) between the paragraph�s top and the beginning of its text content.<br> The default value of this property is 0.0.</td>      </tr>      <tr>       <td>`.lineHeightMultiple`</td>       <td>Line height multiple.</td>       <td>`Float`<br> Example:<br> * `$0.lineHeightMultiple = 1`<br> <br> The natural line height of the receiver is multiplied by this factor (if positive) before being constrained by minimum and maximum line height.<br> The default value of this property is 0.0.</td>      </tr>      <tr>       <td>`.hyphenationFactor`</td>       <td>Paragraph�s threshold for hyphenation.</td>       <td>`Float`<br> Example:<br> * `$0.hyphenationFactor = 1`<br> <br> Hyphenation is attempted when the ratio of the text width (as broken without hyphenation) to the width of the line fragment is less than<br> the hyphenation factor. When the paragraph�s hyphenation factor is 0.0, the layout manager�s hyphenation factor is used instead.<br> When both are 0.0, hyphenation is disabled.</td>      </tr>     </tbody>    </table>    <h2>Installation</h2>    <p>You can install Swiftline using CocoaPods, carthage and Swift package manager</p>    <h3>CocoaPods</h3>    <pre>  <code class="language-swift">use_frameworks!  pod 'SwiftRichString'</code></pre>    <h3>Carthage</h3>    <pre>  <code class="language-swift">github 'malcommac/SwiftRichString'</code></pre>    <h3>Swift Package Manager</h3>    <p>Add swiftline as dependency in your Package.swift</p>    <pre>  <code class="language-swift">import PackageDescription      let package = Package(name: "YourPackage",      dependencies: [        .Package(url: "https://github.com/malcommac/SwiftRichString.git", majorVersion: 0),      ]    )</code></pre>    <h2>Requirements</h2>    <p>Current version is compatible with:</p>    <ul>     <li>Swift 3.0+</li>     <li>iOS 8.0 or later</li>     <li>tvOS 9.0 or later</li>    </ul>    <h2>Credits & License</h2>    <p>SwiftRichString is owned and maintained by <a href="/misc/goto?guid=4959730447852368532" rel="nofollow,noindex">Daniele Margutti</a> .</p>    <p>As open source creation any help is welcome!</p>    <p>The code of this library is licensed under MIT License; you can use it in commercial products without any limitation.</p>    <p>The only requirement is to add a line in your Credits/About section with the text below:</p>    <pre>  <code class="language-swift">This software uses open source SwiftRichString's library to manage rich attributed strings.  Web: http://github.com/malcommac/SwiftRichString  Created by Daniele Margutti and licensed under MIT License.</code></pre>    <p> </p>    <p>来自:https://github.com/malcommac/SwiftRichString</p>    <p> </p>