An easier way to compose attributed strings

Related tags

Text TextAttributes
Overview

Travis Status CocoaPods compatible Carthage compatible Platform

TextAttributes makes it easy to compose attributed strings.

let attrs = TextAttributes()
    .font(name: "HelveticaNeue", size: 16)
    .foregroundColor(white: 0.2, alpha: 1)
    .lineHeightMultiple(1.5)

NSAttributedString(string: "The quick brown fox jumps over the lazy dog", attributes: attrs)

FeaturesUsageDemoReferencesInstallationLicense

Features

  • Strongly typed properties
  • Chainable setter methods
  • A direct access to the NSParagraphStyle properties
  • Better autocompletion

Usage

  • Get or set the TextAttributes properties:
attrs.font = UIFont(name: "HelveticaNeue", size: 16)
attrs.backgroundColor = .white

See all the properties

  • Method chaining:

The TextAttributes methods return Self to allow method chaining:

attrs
    .lineHeightMultiple(1.5)
    .underlineStyle(.styleSingle)

See all the methods

  • The methods are also constructors:

The following are equivalent:

attrs
    .font(name: "HelveticaNeue", size: 16)
    .foregroundColor(white: 0.2, alpha: 1)
let font  = UIFont(name: "HelveticaNeue", size: 16)
let color = UIColor(white: 0.2, alpha: 1)

attrs
    .font(font)
    .foregroundColor(color)
  • Access the underlying dictionary:
attrs.dictionary // Returns the attributes dictionary of type [NSAttributedString.Key: Any]

Third-party libraries:

Demo

Live updates with Injection for Xcode

References

Attributes dictionary

Dictionary Key TextAttributes Property TextAttributes Method
NSFontAttributeName font font(name:size:)
font(_:)
NSParagraphStyleAttributeName paragraphStyle paragraphStyle(_:)
NSForegroundColorAttributeName foregroundColor foregroundColor(_:)
foregroundColor(white:alpha:)
foregroundColor(hue:saturation:brightness:alpha:)
foregroundColor(red:green:blue:alpha:)
foregroundColor(patternImage:)
NSBackgroundColorAttributeName backgroundColor backgroundColor(_:)
backgroundColor(white:alpha:)
backgroundColor(hue:saturation:brightness:alpha:)
backgroundColor(red:green:blue:alpha:)
backgroundColor(patternImage:)
NSLigatureAttributeName ligature ligature(_:)
NSKernAttributeName kern kern(_:)
NSStrikethroughStyleAttributeName strikethroughStyle strikethroughStyle(_:)
NSStrikethroughColorAttributeName strikethroughColor strikethroughColor(_:)
strikethroughColor(white:alpha:)
strikethroughColor(hue:saturation:brightness:alpha:)
strikethroughColor(red:green:blue:alpha:)
strikethroughColor(patternImage:)
NSUnderlineStyleAttributeName underlineStyle underlineStyle(_:)
NSUnderlineColorAttributeName underlineColor underlineColor(_:)
underlineColor(white:alpha:)
underlineColor(hue:saturation:brightness:alpha:)
underlineColor(red:green:blue:alpha:)
underlineColor(patternImage:)
NSStrokeWidthAttributeName strokeWidth strokeWidth(_:)
NSStrokeColorAttributeName strokeColor strokeColor(_:)
strokeColor(white:alpha:)
strokeColor(hue:saturation:brightness:alpha:)
strokeColor(red:green:blue:alpha:)
strokeColor(patternImage:)
NSShadowAttributeName shadow shadow(_:)
shadow(color:offset:blurRadius:)
NSTextEffectAttributeName textEffect textEffect(_:)
NSAttachmentAttributeName attachment attachment(_:)
NSLinkAttributeName link link(_:)
link(string:)
link(string:relativeToURL:)
NSBaselineOffsetAttributeName baselineOffset baselineOffset(_:)
NSObliquenessAttributeName obliqueness obliqueness(_:)
NSExpansionAttributeName expansion expansion(_:)
NSVerticalGlyphFormAttributeName verticalGlyphForm verticalGlyphForm(_:)

Paragraph style

NSMutableParagraphStyle Property TextAttributes Property TextAttributes Method
alignment alignment alignment(_:)
firstLineHeadIndent firstLineHeadIndent firstLineHeadIndent(_:)
headIndent headIndent headIndent(_:)
tailIndent tailIndent tailIndent(_:)
lineBreakMode lineBreakMode lineBreakMode(_:)
maximumLineHeight maximumLineHeight maximumLineHeight(_:)
lineSpacing lineSpacing lineSpacing(_:)
paragraphSpacing paragraphSpacing paragraphSpacing(_:)
paragraphSpacingBefore paragraphSpacingBefore paragraphSpacingBefore(_:)
baseWritingDirection baseWritingDirection baseWritingDirection(_:)
lineHeightMultiple lineHeightMultiple lineHeightMultiple(_:)

Installation

Carthage

Carthage is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate TextAttributes into your Xcode project using Carthage, specify it in your Cartfile:

github "delba/TextAttributes"

Cocoapods

CocoaPods is a dependency manager for Cocoa projects.

You can install it with the following command:

$ gem install cocoapods

To integrate TextAttributes into your Xcode project using CocoaPods, specify it in your Podfile:

use_frameworks!

pod 'TextAttributes'

License

Copyright (c) 2016-2019 Damien (http://delba.io)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Comments
  • Add string, mutableString methods

    Add string, mutableString methods

    I wrote an extension of TextAttributes to enable creating NSAttributedStrings directly, like this:

    let attributedString = TextAttributes()
        .font(name: "HelveticaNeue", size: 16)
        .foregroundColor(white: 0.2, alpha: 1)
        .lineHeightMultiple(1.5)
        .string("The quick brown fox jumps over the lazy dog")
    

    It will be even more easier to create attributed strings. How do you think?

    opened by muukii 10
  • Implements Swift 4 support

    Implements Swift 4 support

    This PR fixes issue https://github.com/delba/TextAttributes/issues/27 by implementing Swift 4.2 support to the project. It has migrated all the source code and all project targets (iOS, MacOS, watch and tvOS) to Swift 4.2. This PR requires Xcode 10 with Swift 4.2 to build successfully.

    There is no change in the API surface and all tests are passing. Please review and merge.

    @delba : If you could add the label hacktoberfest to this PR and the above issue, this would qualify for the Hacktoberfest contest and give some credits.

    opened by annjose 8
  • Update code and project for Swift 4

    Update code and project for Swift 4

    Using xCode 9 beta 3. Was not able to run the tests for some reason, so they are not updated unfortunately. Something to do with the simulators on my machine.

    opened by ejmartin504 8
  • Problem Clone()

    Problem Clone()

    let attribute1 = TextAttributes().font(UIFont(name: "AvenirNext", size: 12))
    
    let attribute2 = attribute1.clone()
    
    attribute2.font  // => UIFont(name: "HelveticaNeue", size: 12) 😥
    attribute2.dictionary[NSFontAttributeName] // => UIFont(name: "AvenirNext", size: 12)
    

    I think that there is better to change StoredProperty to ComputedProperty. How do you think?

    opened by muukii 6
  • TextAttribtues reset paragraphStyle configured by InterfaceBuilder/Storyboard.

    TextAttribtues reset paragraphStyle configured by InterfaceBuilder/Storyboard.

    Hi.

    When migrate my project to TextAttributes I noticed problem and wrote patch for it that is TextAttributes reset paragraphStyle configured by storyboard even if not changed paragraphStyle parameter.

    // `@IBOutlet weak var label: UILabel!` is configured to center alignment via storyboard.
    
    // Native: label is aligned to Center.
    let attributedString = NSMutableAttributedString(string: "text")
    attributedString.addAttribute(NSBaselineOffsetAttributeName, value: 8, range: NSRange(location: 0, length: 4))
    label.attributedText = attributedString
    
    // TextAttributes: label is aligned to Left.
    let attributedString = NSMutableAttributedString(string: "text")
    let attrs = TextAttributes().baselineOffset(8)
    attributedString.addAttributes(attrs)
    label.attributedText = attributedString
    

    Is this bug or feature?

    My workaround patch is this, but this patch break current TextAttributes behavior. https://github.com/r-plus/TextAttributes/commit/680cf0786d0137c1e5bc114aa7d4ff845ecf84dc

    P.S. I preferred current simply architecture. We should add .alignment(.Center) chain explicitly.

    opened by r-plus 4
  • Range

    Range

    Hey there,

    How would I make this work with ranges? Let's say my string is "Hello World". How would I change only the first 5 characters to be red coloured?

    Thanks

    opened by jyounus 2
  • ambiguous use of 'init(string:)

    ambiguous use of 'init(string:)

    On Xcode 7.3 I get this error, "ambiguous use of 'init(string:)", I tried to force the namespace Foundation but it's still ambiguous

    var s = Foundation.NSMutableAttributedString(string: text)
                        ^
    Foundation.NSMutableAttributedString:14:12: note: found this candidate
        public init(string str: String)
               ^
    TextAttributes.NSAttributedString:19:24: note: found this candidate
        public convenience init(string: String, attributes: TextAttributes.TextAttributes? = default)
    
    opened by vhosune 2
  • Support for tvOS, watchOS?

    Support for tvOS, watchOS?

    I would like support for tvOS and watchOS in Podfile. Are there anything blocking support for them?

    s.tvos.deployment_target = '9.0'
    s.wachos.deployment_target = '2.0'
    
    opened by muukii 2
  • Use underlineStyle(.single) cause crash app

    Use underlineStyle(.single) cause crash app

    App Error *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__SwiftValue _getValue:forType:]: unrecognized selector sent to instance 0x2807a3420' Similar https://stackoverflow.com/questions/46092027/setting-nsunderlinestyle-causes-unrecogognized-selector-exception Env: Xcode 11.2

    opened by daoan1412 1
  • Swift 3.0 Update

    Swift 3.0 Update

    I'm not an expect in Swift 3.0 updating, but this works for me when I point my Swift 3 project to my repo.

    Cool library, I haven't dug into it yet but looking forward to it.

    -MikeSand

    opened by mikesanderson 1
  • Remove default value in initilizer

    Remove default value in initilizer

    These convenience initializers conflict existing initializers like this because of the default value in the extension.

    screen shot 2016-04-25 at 13 39 04

    I guess the compiler doesn't recognize which one to use. I think it's not good to affect existing APIs. If you have an idea to this problem, let me know it.

    Thanks in advance.

    opened by pixyzehn 1
Owner
Damien
Damien
A Swifty API for attributed strings

SwiftyAttributes A Swifty API for attributed strings. With SwiftyAttributes, you can create attributed strings like so: let fancyString = "Hello World

Eddie Kaiger 1.5k Jan 5, 2023
Texstyle allows you to format iOS attributed strings easily.

Texstyle allows you to format attributed strings easily. Features Applying attributes with strong typing and autocompletion Cache for attributes Subst

Rosberry 79 Sep 9, 2022
A simple library for building attributed strings, for a more civilized age.

Veneer A simple library for building attributed strings, for a more civilized age. Veneer was created to make creating attributed strings easier to re

Wess Cope 26 Dec 27, 2022
Easiest way to create an attributed UITextView (with support for multiple links and from html)

AttributedTextView Easiest way to create an attributed UITextView (with support for multiple links and html). See the demo app and the playground for

Edwin Vermeer 430 Nov 24, 2022
BonMot is a Swift attributed string library

BonMot (pronounced Bon Mo, French for good word) is a Swift attributed string library. It abstracts away the complexities of the iOS, macOS, tvOS, and

Rightpoint 3.4k Dec 30, 2022
👩‍🎨 Elegant Attributed String composition in Swift sauce

Elegant Attributed String composition in Swift sauce SwiftRichString is a lightweight library which allows to create and manipulate attributed strings

Daniele Margutti 2.9k Jan 5, 2023
More powerful label, attributed string builder and text parser.

DDText More powerful label, attributed string builder and text parser. DDLabel More powerful label than UILabel, using TextKit. It supports features b

Daniel 16 Nov 8, 2022
A quick helper for setting attributed texts to UILabel.

UILabelAttributedTextHelper A quick helper for setting attributed texts to UILabel. Sample usage: label.setAttributedText( leadingText: "H

Glenn Posadas 5 Aug 24, 2022
Easy Attributed String Creator

The main idea of this project is to have an online tool to be able to visually add formatting to a text and get back a swift and/or objective-c code t

Andres Canal 283 Dec 27, 2022
A library for formatting strings on iOS and macOS

Sprinter Introduction What? Why? How? Usage Installation Integration Localization Thread Safety Advanced Usage Introduction What? Sprinter is a librar

Nick Lockwood 168 Feb 6, 2022
🌭 Mustard is a Swift library for tokenizing strings when splitting by whitespace doesn't cut it.

Mustard ?? Mustard is a Swift library for tokenizing strings when splitting by whitespace doesn't cut it. Quick start using character sets Foundation

Mathew Sanders 695 Nov 11, 2022
Converts Markdown files and strings into NSAttributedStrings with lots of customisation options.

SwiftyMarkdown 1.0 SwiftyMarkdown converts Markdown files and strings into NSAttributedStrings using sensible defaults and a Swift-style syntax. It us

Simon Fairbairn 1.5k Dec 22, 2022
A Swift framework for using custom emoji in strings.

Emojica – a Swift framework for using custom emoji in strings. What does it do? Emojica allows you to replace the standard emoji in your iOS apps with

Dan 101 Nov 7, 2022
Generate SwiftUI Text or AttributedString from markdown strings with custom style names.

iOS 15.0 / macOS 12.0 / tvOS 15.0 / watchOS 8.0 StyledMarkdown is a mini library that lets you define custom styles in code and use them in your local

null 19 Dec 7, 2022
_Text is a simple augmentation to SwiftUI that makes styling easier

_Text _Text is a simple augmentation to SwiftUI that makes styling easier. By utilizing the environment it is possible to apply text modifiers to any

Eric Lewis 1 Feb 22, 2022
An easy way to add mentions to uitextview like Facebook and Instagram

OEMentions An easy way to add mentions to uitextview like Facebook and Instagram. It also include a tableview to show the users list to choose from. T

Omar Alessa 48 Oct 23, 2022
PySwiftyRegex - Easily deal with Regex in Swift in a Pythonic way

PySwiftyRegex Easily deal with Regex in Swift in a Pythonic way.

Ce Zheng 232 Oct 12, 2022
Compose is a library that helps you compose complex and dynamic views.

Compose is a data driven library that will help compose your complex and dynamic Views. It helps you create complex and dynamic Views using easy and s

OLX Brasil 123 Jun 9, 2021
GraphQL based Jetpack Compose, Wear Compose and SwiftUI Kotlin Multiplatform sample

GraphQL based Jetpack Compose, Wear Compose and SwiftUI Kotlin Multiplatform sample

John O'Reilly 151 Jan 3, 2023
µframework for Attributed strings.

Attributed µframework for Attributed strings. What is Attributed? Attributed aims to be a drop in replacement to the current version of the NSAttribut

Nicholas Maccharoli 754 Jan 9, 2023