Skip to content

jegnux/Annotated

Repository files navigation

Annotated

Version License Platform

Annotated is a small library that let you annotate your strings with semantic annotations. Once a String is annotated, you can transform it to a NSAttributedString or a SwiftUI Text

It allows you, for example, to semantically annotate a String in your View Model without thinking about the final visual style, and then render your String in your View as an NSAttributedString.

Requirements

  • iOS 11.0
  • Swift 5.1

Installation

Annotated is available through CocoaPods and SwiftPM

Example

First, you need to define your annotations. Using an enum is generally great for that.

enum AddressAnnotations: Hashable {
    case city, postalCode, highlighted
}

Then you can create you Annotated<AddressAnnotations> string using a string literal. You can directly annotate parts of your string thanks to custom String Interpolation.

var string: Annotated<AddressAnnotations> = """
1 Infinite Loop
\("Cupertino", .city), CA \(95014, .postalCode)
"""

You can also add annotations manually.

string.addAnnotation(.highlighted, at: 0..<1)
string.addAnnotation(.highlighted, forOccurencesOf: "in", options: .caseInsensitive)

Finally, you can render your string into an NSAttributedString or a SwiftUI Text using provided factory methods.

let attributedString = string.makeAttributedString { annotation in
  switch annotation {
  case nil:          return [.font: UIFont.systemFont(ofSize: 24)]
  case .city:        return [.font: UIFont.boldSystemFont(ofSize: 24)]
  case .postalCode:  return [.underlineStyle: NSNumber(value: NSUnderlineStyle.single.rawValue)]
  case .highlighted: return [.foregroundColor: UIColor.systemRed]
  }
}
let text = string.makeText { annotation in
  switch annotation {
  case nil:          return { $0.font(.system(size: 24)) }
  case .city:        return { $0.bold() }
  case .postalCode:  return { $0.underline() }
  case .highlighted: return { $0.foregroundColor(.red) }
  }
}

Author

Jérôme Alves

License

Annotated is available under the MIT license. See the LICENSE file for more info.

About

Annotate your Strings

Resources

License

Stars

Watchers

Forks

Packages

No packages published