Programmatic creation of NSAttributedString doesn't have to be a pain

Related tags

Text Tribute
Overview

Tribute Build Status

let string = NSMutableAttributedString().add("Hello ") {
    $0.font = .systemFontOfSize(20)
    $0.color = .redColor()
    $0.underline = .StyleSingle
}.add("world ") {
    $0.stroke = .Filled(width: 2)
    $0.strokeColor = .orangeColor()
}.add("of Swift "){
    $0.font = .systemFontOfSize(12)
    $0.underline = nil
    $0.URL = NSURL(string: "http://swift.org")!
}.add(UIImage(named: "swift")!)

Not bad comparing to

let string2 = NSMutableAttributedString()
string2.appendAttributedString(NSAttributedString(string: "Hello ", attributes: [
    NSFontAttributeName: UIFont.systemFontOfSize(20),
    NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue,
    NSForegroundColorAttributeName: UIColor.redColor()
]))
string2.appendAttributedString(NSAttributedString(string: "world ", attributes: [
    NSFontAttributeName: UIFont.systemFontOfSize(20),
    NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue,
    NSForegroundColorAttributeName: UIColor.redColor(),
    NSStrokeColorAttributeName: UIColor.orangeColor(),
    NSStrokeWidthAttributeName: -2
]))
string2.appendAttributedString(NSAttributedString(string: "of Swift ", attributes: [
    NSFontAttributeName: UIFont.systemFontOfSize(12),
    NSForegroundColorAttributeName: UIColor.redColor(),
    NSStrokeColorAttributeName: UIColor.orangeColor(),
    NSStrokeWidthAttributeName: -2
]))
let attachment = NSTextAttachment()
attachment.image = UIImage(named: "swift")
string2.appendAttributedString(NSAttributedString(attachment: attachment))

Design Goals

  1. Word processor logic: appending a string should inherit last attributes.
  2. Allow for easy customization of common properties, including toggle bold or change the font size.
  3. Flatten paragraph style and attributes, no more 5 lines of code if all you wanted is to change text alignment.
  4. Replace weird attributes with more reasonable versions (for example Attribute.Stroke vs NSStrokeWidthAttributeName).
  5. Minimal overhead: produce only required attributes.
  6. Have an attributed string ready to use every time you leave the configuration block.
  7. Replace string constants with strongly typed enums where possible.

Notes

Playground

Playgrounds do not always render NSAttributesString correctly (font variations and attachments are few of the problematic I noticed).

Workaround: Use a UILabel as a live view instead: XCPlaygroundPage.currentPage.liveView = label.

Font variations

Not all fonts have both italic and bold variations

Workaround: Use obliqueness property as a poor man italic, and expansion as a bold respectively.

Closure with one statement

When the configuration closure includes only one statement, compiler gets confused

Workaround: Specify closure type explicitly like so

string.add("text") { (inout a: Attributes) in
    a.color = .redColor()
}

If you know a better way, please open a PR, I'd love to learn from it!

Roadmap

  • Objective-C compatibility
  • Moar attributes (PRs are welcome)

This is just a tribute

You might also like...
LDOMarkdownParser - Parse (some) markdown attributes into an NSAttributedString

LDOMarkdownParser Description Convert markdown text styling into an NSAttributed

AttributedText is a Swift µpackage that provides NSAttributedString rendering in SwiftUI by wrapping either an NSTextView or a UITextView depending on the platform.
AttributedText is a Swift µpackage that provides NSAttributedString rendering in SwiftUI by wrapping either an NSTextView or a UITextView depending on the platform.

AttributedText AttributedText is a Swift µpackage that provides NSAttributedString rendering in SwiftUI by wrapping either an NSTextView or a UITextVi

A powerful Swift programmatic UI layout framework.
A powerful Swift programmatic UI layout framework.

Build dynamic and beautiful user interfaces like a boss, with Swift. Neon is built around how user interfaces are naturally and intuitively designed.

Programmatic UI for macOS
Programmatic UI for macOS

Description: Programmatic UI Framework for macOS. Swift handles app logic, CSS/SVG handles design and JSON handles struture. Installation: Step 1: Add

An alternative SwiftUI NavigationView implementing classic stack-based navigation giving also some more control on animations and programmatic navigation.
An alternative SwiftUI NavigationView implementing classic stack-based navigation giving also some more control on animations and programmatic navigation.

swiftui-navigation-stack An alternative SwiftUI NavigationView implementing classic stack-based navigation giving also some more control on animations

A wrapper for NavigationView and NavigationLink that makes programmatic navigation a little friendlier.

NavigatorKit A wrapper for NavigationView and NavigationLink that makes programmatic navigation a little friendlier. NavigatorKit is an opinionated wr

Convenient domain specific language for writing programmatic UI built over UIKit and more.

XYKit Swifty and convenient domain specific language for creating programmatic UI in a more declarative way and more than that. Built on top of UIKit

Programmatic view layout for the rest of us.
Programmatic view layout for the rest of us.

Façade Important Facade is no longer under active development, and as such if you create any issues or submit pull requests, it's not very likely to b

Concise Auto Layout API to chain programmatic constraints while easily updating existing constraints.
Concise Auto Layout API to chain programmatic constraints while easily updating existing constraints.

Concise API for Auto Layout. SnapLayout extends UIView and NSView to deliver a list of APIs to improve readability while also shortening constraint co

A Simple Camera App With Programmatic UI
A Simple Camera App With Programmatic UI

CameraApp-ProgrammaticUI Hey there! This is a simple Camera Application that I and Sahab Alharbi worked on as part of Tuwaiq's iOS bootcamp projects.

A lightweight iOS mini framework that enables programmatic navigation with SwiftUI, by using UIKit under the hood.

RouteLinkKit A lightweight iOS mini framework that enables programmatic navigation with SwiftUI. RouteLinkKit is fully compatible with native Navigati

Swifty DSL for programmatic Auto Layout in iOS
Swifty DSL for programmatic Auto Layout in iOS

WWLayout Easy to write auto layout constraints, with minimal extensions to standard namespaces. Feature Highlights Easy to use, readable API Backwards

nef💊a toolset to ease the creation of documentation in the form of Xcode Playgrounds
nef💊a toolset to ease the creation of documentation in the form of Xcode Playgrounds

nef, short for Nefertiti, mother of Ankhesenamun, is a toolset to ease the creation of documentation in the form of Xcode Playgrounds. It provides com

CompositionalLayoutDSL, library to simplify the creation of UICollectionViewCompositionalLayout. It wraps the UIKit API and makes the code shorter and easier to read.
CompositionalLayoutDSL, library to simplify the creation of UICollectionViewCompositionalLayout. It wraps the UIKit API and makes the code shorter and easier to read.

CompositionalLayoutDSL CompositionalLayoutDSL is a Swift library. It makes easier to create compositional layout for collection view. Requirements Doc

iOS On-Device Game Cheat Creation/Sharing Platform and Software

CheatManager CheatManager is a mobile platform, used for installation/distribution/creation of mobile game cheats/hacks. This platform is completely d

A simple SwiftUI Application to demonstrate creation of UI using SwiftUI.
A simple SwiftUI Application to demonstrate creation of UI using SwiftUI.

WatchShop_UI A simple SwiftUI Application to demonstrate creation of UI using SwiftUI. How to run the project ? Fork the project. Run the project usin

 It is a music and podcast creation system that enables users to create multiple tracks using AR(Augmented Reality).
It is a music and podcast creation system that enables users to create multiple tracks using AR(Augmented Reality).

AR-Studio It is a music creation system enables users to create multiple tracks using AR(Augmented Reality). Introduction AR Studio turns your iPad, a

Magical Data Modeling Framework for JSON - allows rapid creation of smart data models. You can use it in your iOS, macOS, watchOS and tvOS apps.

JSONModel - Magical Data Modeling Framework for JSON JSONModel allows rapid creation of smart data models. You can use it in your iOS, macOS, watchOS

Magical Data Modeling Framework for JSON - allows rapid creation of smart data models. You can use it in your iOS, macOS, watchOS and tvOS apps.

JSONModel - Magical Data Modeling Framework for JSON JSONModel allows rapid creation of smart data models. You can use it in your iOS, macOS, watchOS

Comments
  • Swift 5 Support

    Swift 5 Support

    I found this library very useful but it was required so many changes to make this repository in a state to work with latest swift 5. I Did all the changes and now this works with latest swift 5 version. Cheers...

    opened by VickyPrajapati24 1
Owner
Sash Zats
┬─┬ ノ( ゜- ゜ノ)
Sash Zats
Leverages Apple's Swift-based Markdown parser to output NSAttributedString.

Markdownosaur ?? Markdownosaur uses Apple's excellent and relatively new Swift Markdown library to analyze a Markdown source, and then takes that anal

Christian Selig 232 Dec 20, 2022
Type strict builder class for NSAttributedString.

StringStylizer Type strict builder class for NSAttributedString. What's this? StringStylizer makes NSAttributedString more intuitive with Method chain

Kazuhiro Hayashi 75 Nov 11, 2022
LDOMarkdownParser - Parse (some) markdown attributes into an NSAttributedString

LDOMarkdownParser Description Convert markdown text styling into an NSAttributed

Lurado 1 Feb 4, 2022
AttributedText is a Swift µpackage that provides NSAttributedString rendering in SwiftUI by wrapping either an NSTextView or a UITextView depending on the platform.

AttributedText AttributedText is a Swift µpackage that provides NSAttributedString rendering in SwiftUI by wrapping either an NSTextView or a UITextVi

null 1 Jul 18, 2022
URLScheme router than supports auto creation of UIViewControllers for associated url parameters to allow creation of navigation stacks

IKRouter What does it do? Once you have made your UIViewControllers conform to Routable you can register them with the parameters that they represent

Ian Keen 94 Feb 28, 2022
Convert text with HTML tags, links, hashtags, mentions into NSAttributedString. Make them clickable with UILabel drop-in replacement.

Atributika is an easy and painless way to build NSAttributedString. It is able to detect HTML-like tags, links, phone numbers, hashtags, any regex or

Pavel Sharanda 1.1k Dec 26, 2022
Convert text with HTML tags, links, hashtags, mentions into NSAttributedString. Make them clickable with UILabel drop-in replacement.

Atributika is an easy and painless way to build NSAttributedString. It is able to detect HTML-like tags, links, phone numbers, hashtags, any regex or

Pavel Sharanda 1.1k Jan 8, 2023
Convert text with HTML tags, links, hashtags, mentions into NSAttributedString. Make them clickable with UILabel drop-in replacement.

Convert text with HTML tags, links, hashtags, mentions into NSAttributedString. Make them clickable with UILabel drop-in replacement.

Pavel Sharanda 1.1k Dec 26, 2022
Leverages Apple's Swift-based Markdown parser to output NSAttributedString.

Markdownosaur ?? Markdownosaur uses Apple's excellent and relatively new Swift Markdown library to analyze a Markdown source, and then takes that anal

Christian Selig 232 Dec 20, 2022
Type strict builder class for NSAttributedString.

StringStylizer Type strict builder class for NSAttributedString. What's this? StringStylizer makes NSAttributedString more intuitive with Method chain

Kazuhiro Hayashi 75 Nov 11, 2022