Texstyle allows you to format iOS attributed strings easily.

Related tags

Text texstyle
Overview

Stylin

Swift Version Carthage Compatible codecov

Texstyle allows you to format attributed strings easily.

Features

  • Applying attributes with strong typing and autocompletion
  • Cache for attributes
  • Substyles
  • Convenient extensions for String and UIButton

Requirements

  • iOS 9.0+ / tvOS 9.0+
  • Xcode 10.0+

Usage

Here is a basic example of Texstyle using:

let text = Text(value: "Hello, World 🌍", style: .title1)
text.add(.heading1, for: "World")
titleLabel.attributedText = text.attributed

The result:

Example1

Let's start with text styles. There is a TextStyle class for configuring different style parameters like font, color, kerning etc. We prefer to use TextStyle extension for app specific styles:

extension TextStyle {

    static let title1: TextStyle = {
        let style = TextStyle()
        style.font = .systemFont(ofSize: 32, weight: .regular)
        return style
    }()
        
    static let heading1: TextStyle = {
        let style = TextStyle()
        style.font = .systemFont(ofSize: 28, weight: .semibold)
        style.color = .purple
        return style
    }()
}

It allows you to reuse the styles across the app.

Next, create a Text instance. It contains string value and style:

let text = Text(value: "Hello, World 🌍", style: .title1)

Text also supports independent styles for each UIControl.State. For example, if you want to use a different style for button highlight state, you should initialize text like:

let text = Text(value: " Sign in with Apple", styles: [.normal: .heading1,
                                                         .highlighted: .heading2])

To create an attributed string, just use:

//By default for normal state
text.attributed

//For needed state
text.attributed(for: .highlighted)

All attributed strings are cached by default. It's useful in reusable elements like UICollectionViewCell or UITableViewCell.

There are custom operators for texts and strings:

let text1 = Text(value: "Ros", style: .title1)
let text2 = text1 + "ber"
let text3 = Text(value: "ry", style: .title1)
let text4 = text2 + text3
text4.value // "Rosberry"

There are convenience APIs for text creation and applying:

//String to text
"Settings".text(with: .heading1)

//UIButton
button.setText(text)

Check TexstyleExample project for more examples.

Example2

Cache

TextStyle and Text classes have internal cache to prevent extra calculation. TextStyle caches attributes and invalidates it on any attribute change. Text has cached attributed strings for states. For example, if you use texts in collection view cells and want to update some labels in it after reuse, texts return cached strings. Please note that texts won't invalidate cached strings if you update textstyle attributes.

Installation

Depo

Depo is a universal dependency manager that combines Carthage, SPM and CocoaPods and provides common user interface to all of them.

To install Texstyle via Carthage using Depo you need to add this to your Depofile:

carts:
  - kind: github
    identifier: rosberry/Texstyle
To install Texstyle via CocoaPods Add this to your Depofile:
pods:
  - name: Texstyle

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate Alamofire into your Xcode project using CocoaPods, specify it in your Podfile:

pod 'Texstyle', '~> 0.0'

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate Alamofire into your Xcode project using Carthage, specify it in your Cartfile:

5.0 ">
github "Rosberry/Texstyle" ~> 5.0

Documentation

Read the docs. Generated with jazzy. Hosted by GitHub Pages.

About

This project is owned and maintained by Rosberry. We build mobile apps for users worldwide 🌏 .

Check out our open source projects, read our blog or give us a high-five on 🐦 @rosberryapps.

License

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

Comments
  • Equatable

    Equatable

    I added missing Equatable conformance for Text class. Related to https://github.com/rosberry/texstyle/issues/2. There was an idea to calculate a hash for every Text and textStyle change to speed up the equality check. But what if I don't need to compare the texts? We decided to leave the implementation as is, but we need @disabled opinion here.

    opened by artemnovichkov 2
  • Support Require Only App-Extension-Safe API

    Support Require Only App-Extension-Safe API

    There is a limitation to this for extension. And the compiler warns about this when you import the frameworks into Extension - “warning: binding with dylib is unsafe for use in application extensions”. By setting the flag APPLICATION_EXTENSION_API_ONLY = YES; We guarantee the extension that we do not use unavailable API.

    opened by ReshetovE 1
  • Cache

    Cache

    Update README with the cache logic description. Related to #14. BTW, add missing texts for arrays.

    Implement text style property observing

    Implemented Observer pattern for text style object with flex memory management

    opened by artemnovichkov 1
  • 🔢 Enhancements

    🔢 Enhancements

    There are some useful changes in this request. I decided to combine it into one PR to reduce code review hell :) Here is a checklist for the changes:

    • Array extension for texts joining. Supports custom separator
    • Custom + operator for texts and strings
    • Add missing attributes: ligature, shadow, strokeColor
    • Add string concatenation for text
    opened by artemnovichkov 1
  • Bounding rects

    Bounding rects

    I added Text function for bounding rect calculation. There are default parameters, so for common case you should pass only constrained size. Please check related tests for more examples. Related to https://github.com/rosberry/texstyle/issues/3

    opened by artemnovichkov 1
  • Dynamic linking

    Dynamic linking

    I used static linking for Texstyle, but @medvedzzz had an issue with project builds. The problem is related to code coverage (strange, right?) according to this issue. So I've updated the project with dynamic linking

    opened by artemnovichkov 1
  • Default values for line break mode and alignment

    Default values for line break mode and alignment

    By default UILabel uses .natural text alignment and .byTruncatingTail line break mode. To leave default behaviour as is I added these default values to all styles. Related to #13

    enhancement 
    opened by artemnovichkov 0
  • Shadow style

    Shadow style

    Add a style for shadows

    import UIKit
    
    open class ShadowStyle {
    
        public var opacity: CGFloat = 0.0
        public var radius: CGFloat = 0.0
        public var offset: CGSize = .zero
        public var color: UIColor = .clear
    
        var shadow: NSShadow {
            let shadow = NSShadow()
            shadow.shadowBlurRadius = radius
            shadow.shadowOffset = offset
            shadow.shadowColor = color.withAlphaComponent(opacity)
            return shadow
        }
    }
    
    // MARK: - Equatable
    
    extension ShadowStyle: Equatable {
        public static func == (lhs: ShadowStyle, rhs: ShadowStyle) -> Bool {
            return lhs.color == rhs.color &&
                   lhs.offset == rhs.offset &&
                   lhs.radius == rhs.radius &&
                   lhs.opacity == rhs.opacity
        }
    }
    
    enhancement 
    opened by artemnovichkov 0
  • README and example

    README and example

    • Update README with configuring example
    • Update the example with common use cases. 👻 Attension: enable "Display the rish diff" to see README formatting
    opened by artemnovichkov 0
  • Bounding rects

    Bounding rects

    Add bounding rect calculation to Text object like:

        ///Returns the bounding rectangle required to draw the string.
        ///
        /// - Parameters:
        ///   - size: The width and height constraints to apply when computing the string’s bounding rectangle.
        ///   - options: Additional drawing options to apply to the string during rendering.
        ///   - context: A context object with information about how to adjust the font tracking and scaling information.
        /// On return, the specified object contains information about the actual values used to render the string.
        /// This parameter is nil by default.
        ///   - state: The control state for attributes.
        /// - Returns: A rectangle whose size component indicates the width and height required to draw the entire contents of the string.
        public func boundingRect(with size: CGSize,
                                 options: NSStringDrawingOptions = [.usesLineFragmentOrigin, .usesFontLeading],
                                 context: NSStringDrawingContext? = nil,
                                 for state: ControlState = .normal) -> CGRect {
            guard let attributedString = attributed(for: state) else {
                return .zero
            }
            return attributedString.boundingRect(with: size, options: options, context: context)
        }
    
    enhancement 
    opened by artemnovichkov 0
Releases(0.5)
Owner
Rosberry
Rosberry
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
An easier way to compose attributed strings

TextAttributes makes it easy to compose attributed strings. let attrs = TextAttributes() .font(name: "HelveticaNeue", size: 16) .foregroundCol

Damien 2.2k Dec 31, 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
UITextField realtime currency formatter - format while typing

Objective-C Realtime Currency Formatter An extremely simple Objective-C class for formatting currencies. Ready to work with the UITextFieldDelegate an

Kaio Medau 14 Jul 28, 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
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
Easily show RichText(html) in SwiftUI

RichText LightMode DarkMode Code import SwiftUI

null 82 Jan 7, 2023
🖍 Highlight whatever you want!

Highlighter Updates See CHANGELOG for details Intoduction ?? Highlight whatever you want! Highlighter will magically find UI objects such as UILabel,

Kyle Yi 933 Dec 29, 2022
Fully open source text editor for iOS written in Swift.

Edhita Fully open source text editor for iOS written in Swift. http://edhita.bornneet.com/ What Edhita means? Edhita (Romaji) == エディタ (Katakana) == Ed

Tatsuya Tobioka 1.2k Jan 1, 2023