Type strict builder class for NSAttributedString.

Overview

StringStylizer

Carthage compatible Cocoapods compatible Swift 5.0

Type strict builder class for NSAttributedString.

What's this?

StringStylizer makes NSAttributedString more intuitive with Method chain and Operator. Building NSAttributedString is so difficult because it requires us to remember attribute names and types. If you do that with StringStylizer, There is no need to remember them 😃

NSAttributedString has the following format.

let attr: [NSAttributedString.Key: Any] = [
    .foregroundColor: UIColor.white,
    .font: UIFont(name: "HelveticaNeue", size: 14)
]
let str = NSAttributedString(string: "some text", attributes: attr)

StringStylizer enable developers to read and write their code in a linear manner. If you wanna convert String to NSAttributedString which has some colors, sizes and fonts, you can write that as follows.

let str = "some text".stylize().color(.white).size(14).font(.HelveticaNeue).attr

Feature

  • Type strict format
  • Assigning ranges and attributes in a linear manner
  • More readable than NSAttributedString

Requirements

  • iOS 8.0+
  • Swift 5.0~ or Swift 4.0~ or Swift 3.2~

Installation

Carthage

  • Install Carthage from Homebrew
> ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
> brew update
> brew install carthage
  • Move your project dir and create Cartfile
> touch Cartfile
  • add the following line to Cartfile
github "kazuhiro4949/StringStylizer"
  • Create framework
> carthage update --platform iOS
  • In Xcode, move to "Genera > Build Phase > Linked Frameworks and Library"
  • Add the framework to your project
  • Add a new run script and put the following code
/usr/local/bin/carthage copy-frameworks
  • Click "+" at Input file and Add the framework path
$(SRCROOT)/Carthage/Build/iOS/StringStylizer.framework
  • Write Import statement on your source file
import StringStylizer

CocoaPods

  • Install CocoaPods
> gem install cocoapods
> pod setup
  • Create Podfile
> pod init
  • Edit Podfile
# Uncomment this line to define a global platform for your project
platform :ios, '8.0'  # add
use_framework!  # add

target 'MyAppName' do
  pod 'StringStylizer' # add
end

target 'MyAppTests' do

end

target 'MyAppUITests'
  • Install
> pod install

open .xcworkspace

Example

let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 50))

// build NSAttributedString.
let greeting = "Hi, ".stylize().color(0x2200ee).size(12).font(.HelveticaNeue).attr

// build NSAttributedString with ranges.
let msg = "something happened ".stylize()
    .range(0..<9)        .color(0x009911).size(12).font(.HelveticaNeue)
    .range(10..<UInt.max).color(0xaa22cc).size(14).font(.HelveticaNeue_Bold).attr

// build NSAttributedString objects and join them.
let name = "to ".stylize().color(0x23abfc).size(12).font(.HelveticaNeue).attr +
    "you".stylize().color(0x123456).size(14).font(.HelveticaNeue_Italic).underline(.double).attr
    
// build NSAttributedString objects with strikethrough and kerning applied.
let response = "\nHow ".stylize().attr +  "boring".stylize().strikeThrough(.single).attr +
    " exciting!".stylize().kern(-2).attr

This sample generates a styled label.

Of course, you can wrap up the method chains.

extension StringStylizer {
  func strong() -> NSAttributedString {
    return self
            .color(0x123456)
            .size(14)
            .font(.HelveticaNeue_Italic)
            .underline(.double)
            .attr
  }
}

label.attributedText = "you".stylize().strong()

Usage

1. Convert String to StringStylizer object

let firstStep = "yay!".stylize() // => StringStylizer<Styling>
1a. Alternatively, use an optional String
let optionalString:String? = nil
let firstStep = optionalString.stylize() // => StringStylizer<Styling>

2. Call methods to select range. Then, StringStylizer change into "NarrowDown" state

let secondStep = "yay!".stylize().range(0..<UInt.max) // => StringStylizer<NarrowDown>

3. Call methods to set attributes. Then, StringStylizer change into "Styling" state

let thirdStep = "yay!".stylize().range(0..<UInt.max).size(14) // => StringStylizer<Styling>

4. Convert to NSAttributedString object.

let fourthStep = "yay!".stylize().range(0..<UInt.max).size(14).attr // => NSAttributedString

5. Join another NSAttributedString object.

let one     = "yay!".stylize().range(0..<UInt.max).size(14).attr
let another = " yay!".stylize().color(0xffffff).attr
let fifthStep = one + another // => NSAttributedString

That's it!

Architecture

StringStylizer is based on "Builder Pattern" (Effective Java version). In addition, it has states managed by "Phantom Type".

Because of them, we are able to

  • write our code in a linear manner
  • call proper methods depending on the situation.

License

Copyright (c) 2016 Kazuhiro Hayashi

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.

You might also like...
Type-safe networking abstraction layer that associates request type with response type.

APIKit APIKit is a type-safe networking abstraction layer that associates request type with response type. // SearchRepositoriesRequest conforms to Re

A phantom type is a custom type that has one or more unused type parameters.

PhantomTypes A phantom type is a custom type that has one or more unused type parameters. Phantom types allow you to enforce type-safety without sacri

Simple UIAlertController builder class in Swift.
Simple UIAlertController builder class in Swift.

Kamagari Simple UIAlertController builder class in Swift. Features AlertBuilder class to simply build UIAlertController by using method chaining UIAle

Setup your class structure in Xcode Interface Builder and save() in Parse Server.
Setup your class structure in Xcode Interface Builder and save() in Parse Server.

ISParseBind With ISParseBind you can save, update and query PFObjects using the power of Xcode Interface Builder resources. https://www.youtube.com/wa

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.

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

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.

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

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.

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

Leverages Apple's Swift-based Markdown parser to output NSAttributedString.
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

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

Tribute let string = NSMutableAttributedString().add("Hello ") { $0.font = .systemFontOfSize(20) $0.color = .redColor() $0.underline = .St

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 fast, convenient and nonintrusive conversion framework between JSON and model. Your model class doesn't need to extend any base class. You don't need to modify any model file.

MJExtension A fast, convenient and nonintrusive conversion framework between JSON and model. 转换速度快、使用简单方便的字典转模型框架 📜 ✍🏻Release Notes: more details Co

A simple class that wraps the process of saving or loading a struct or class into a single file

EZFile This is a simple class that wraps the process of saving or loading a stru

Xcode Plugin helps you find missing methods in your class header, protocols, and super class, also makes fast inserting.

FastStub-Xcode Life is short, why waste it on meaningless typing? What is it? A code generating feature borrowed from Android Studio. FastStub automat

MemoryCache - type-safe, thread-safe memory cache class in Swift

MemoryCache is a memory cache class in swift. The MemoryCache class incorporates LRU policies, which ensure that a cache doesn’t

Type-safe CAAnimation wrapper. It makes preventing to set wrong type values.
Type-safe CAAnimation wrapper. It makes preventing to set wrong type values.

TheAnimation TheAnimation is Type-safe CAAnimation wrapper. Introduction For example, if you want to animate backgroundColor with CABasicAnimation, yo

Design and prototype customized UI, interaction, navigation, transition and animation for App Store ready Apps in Interface Builder with IBAnimatable.
Design and prototype customized UI, interaction, navigation, transition and animation for App Store ready Apps in Interface Builder with IBAnimatable.

Design and prototype customized UI, interaction, navigation, transition and animation for App Store ready Apps in Interface Builder with IBAnimatable.

Localize your views directly in Interface Builder with IBLocalizable
Localize your views directly in Interface Builder with IBLocalizable

Localize your views easily in Interface Builder with IBLocalizable. With IBLocalizable, you can localize your views in Interface Builder easily. Simpl

🌸 Powerful Codable API requests builder and manager for iOS.
🌸 Powerful Codable API requests builder and manager for iOS.

This lib is about network requests with blackjack, roulette and craps! Using it you will be able to convert your massive API layer code into an awesom

Comments
  • minor typos fixes, a potential optional addition,  and some more example usage

    minor typos fixes, a potential optional addition, and some more example usage

    Hey kazuhiro,

    Firstly, I love this framework. it makes many many many gross terrible things much nicer to read and write through the builder-style pattern.

    In this PR, I have corrected a couple of typo's, so that it is easier to discover this framework's functionality.

    I also have added an optional extension - which makes it easier to use an optional String with StringStylizer.

    Let me know what you think!

    opened by salguodnz 3
  • Add support for Swift 4.2

    Add support for Swift 4.2

    Swift 4.2 renames NSAttributedStringKey to NSAttributedString.Key and NSUnderlineStyle cases like .styleSingle to .single. This PR uses #if swift(>4.2) checks to simultaneously support both Swift 4.2 and lower versions.

    opened by u2606 1
  • create method for shadow

    create method for shadow

    shadow(_:) receives only NSShadow object.
    https://github.com/kazuhiro4949/StringStylizer/blob/master/StringStylizer/StringStylizer.swift#L370

    I would like to call a shadow method with NSShadow properties.

    "shadow".stylize().shadow(offset: (0, 5), color: 0xff0000, blurRadius: 1).attr
    
    opened by kazuhiro4949 1
  • [suggestion]: Conditionals made first-class citizens as part of the StringStylizer DSL

    [suggestion]: Conditionals made first-class citizens as part of the StringStylizer DSL

    Hey Kazuhiro,

    I'm not sure if you would want to support this kind of use-case, but consider the following.

    Here is a bunch of some of the more convoluted string formation we have.

      let descAttrStrBuilder = promotion.dealDescription.stylize()
                .color(.normalContentTitle())
                .font(.preferredFont(forTextStyle: .subheadline))
            
            if promotion.isPromotionActionable {
                descAttrStrBuilder.underline(.single)
            }
            
            let descAttrStr = descAttrStrBuilder.attr
            
            var validUntil: String?
            if let endsDate = promotion.offerEndsDate {
                let endsDateString = DateFormatter.localizedString(from: endsDate, dateStyle: .short, timeStyle: .none)
                validUntil = "\nOffer Ends: \(endsDateString)"
            }
            
            let endDateAttrStr = validUntil.stylize()
                .color(.normalContentSubTitle())
                .font(.preferredFont(forTextStyle: .footnote))
                .attr
            
            titleLabel.attributedText = descAttrStr + endDateAttrStr
    

    for the promotion.isPromotionActionable block - I wonder if this is something that could be made a 'first class' citizen of the current StringStylizer DSL.

    What I mean by this is, It would be cool to write that if block 'in-line' like one of the below two syntaxes.

    descAttrStrBuilder.conditionally(promotion.isPromotionActionable).underline(.single)
    

    OR

    descAttrStrBuilder.underline(.single, conditionally: promotion.isPromotionActionable)
    

    Option 1 - would mean adding more state into StringStylizer - when a conditionally() is used, you would need to evaluate that in the next 'style code' call (i.e. underline()) and then reset it. The only issue I have with this is if there is more than 1 'style code' method called. i.e. stylizer.conditionally(true).underline(.single).color(black) Does the conditional apply to both underline() and color()? That question is something that this syntax couldn't really communicate unless you were to change conditionally to conditionallySingle() and conditionallyAll() or something like this. It still isn't necessarily natural to consume though.

    Option 2 - would be probably easier to understand as a framework consumer - and perhaps could be optional and default to nil or true :). It is not quite as pretty looking as option 1 however.

    Either way would involve a pretty decent rewrite. I would be happy to help out if you like such a suggestion. Or alternatively, of course, you could suggest a better way to write the above snippet 😬

    opened by salguodnz 0
Releases(5.3)
Owner
Kazuhiro Hayashi
Kazuhiro Hayashi
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
Programmatic creation of NSAttributedString doesn't have to be a pain

Tribute let string = NSMutableAttributedString().add("Hello ") { $0.font = .systemFontOfSize(20) $0.color = .redColor() $0.underline = .St

Sash Zats 63 Sep 24, 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
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
Introducing with Xcode Storyboard and Interface Builder

I-am-rich Introducing with Xcode Storyboard and Interface Builder Introducing wi

null 0 Dec 17, 2021
Regex class for Swift. Wraps NSRegularExpression.

Regex.swift install Use CocoaPods. Add to your Podfile: pod 'Regex' And then run pod install from the shell: $ pod install usage Simple use cases: Str

Bryn Bellomy 67 Sep 14, 2022
Decodable Simple and strict, yet powerful object mapping made possible by Swift 2's error handling.

Decodable Simple and strict, yet powerful object mapping made possible by Swift 2's error handling. Greatly inspired by Argo, but without a bizillion

Johannes Lund 1k Jul 15, 2022
Overload +-*/ operator for Swift, make it easier to use (and not so strict)

Easy-Cal-Swift Overview This file is an overloading of +-*/ operator for Swift, to make it easier to use (and not so strict) It can make your life wit

Wei Wang 272 Jun 29, 2022
This framework implements a strict JSON parser and generator in Objective-C.

SBJson 5 Chunk-based JSON parsing and generation in Objective-C. Overview SBJson's number one feature is stream/chunk-based operation. Feed the parser

null 3.8k Jan 5, 2023