• Stars
    star
    1,511
  • Rank 31,023 (Top 0.7 %)
  • Language
    Objective-C
  • Created almost 14 years ago
  • Updated almost 10 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

UILabel that supports NSAttributedString

Depreciation warning!

Unfortunately, I no longer have time to maintain this class. Moreover, as since iOS6, UILabel now natively support NSAttributedStrings, this component is totally obsolete now (and maintaining it requires a lot of work for little benefit with recent projects all supporting iOS6+).

Note: If you are willing to take the lead and continue to make it evolve, feel free to contact me so I can give you some GIT access ton continue to maintain it.

Migrating away from OHAttributedLabel

For iOS6+ apps

If you need only to support iOS6+, you can use UILabel and its native support for NSAttributedString, and use my new OHAttributedStringAdditions pod to build your NSAttributedStrings more easily.

Note that OHAttributedLabel's NSAttributedString categories are building CoreText-only compatible strings and are not compatible with UILabel and UIKit/TextKit's handling of NSAttributedString introduced in iOS6. That's why you need to use OHAttributedStringAdditions instead.

iOS6+'s NSAttributedString and TextKit now supports a wide range of possibilities (making OHAttributedLabel useless anyway), letting you parse safe HTML, include attachements (images) and links, etc. So it even fits for advanced usages. See the example project in OHAttributedStringAdditions repository.

For very advanced usages or apps supporting iOS5 or earlier

If you still need to support iOS versions 5 or earlier, I strongly recommand the DTCoreText library by @Cocoanetics as a replacement — which is a way more complete framework that my own library and let you do much more stuff.


Table of Contents


About these classes

OHAttributedLabel

This class allows you to use a UILabel with NSAttributedStrings, in order to display styled text with various style (mixed fonts, color, size, ...) in a unique label. It is a subclass of UILabel which adds an attributedText property. Use this property, instead of the text property, to set and get the NSAttributedString to display.

Note: This class is compatible with iOS4.3+ and has been developped before the release of the iOS6 SDK (before Apple added support for NSAttributedLabel in the UILabel class itself). It can still be used with the iOS6 SDK (the attributedText property hopefully match the one chosen by Apple) if you need support for eariler iOS versions or for the additional features it provides.

This class also support hyperlinks and URLs. It can automatically detect links in your text, color them and make them touchable; you can also add "custom links" in your text by attaching an URL to a range of your text and thus make it touchable, and even then catch the event of a touch on a link to act as you wish to.

NSAttributedString and NSTextChecking additions

In addition to this OHAttributedLabel class, you will also find a category of NS(Mutable)AttributedString to ease creation and manipulation of common attributes of NSAttributedString (to easily change the font, style, color, ... of a range of the string). See the header file NSAttributedString+Attributes.h for a list of those comodity methods.

Example:

// Build an NSAttributedString easily from a NSString
NSMutableAttributedString* attrStr = [NSMutableAttributedString attributedStringWithString:txt];
// Change font, text color, paragraph style
[attrStr setFont:[UIFont fontWithName:@"Helvetica" size:18]];
[attrStr setTextColor:[UIColor grayColor]];

OHParagraphStyle* paragraphStyle = [OHParagraphStyle defaultParagraphStyle];
paragraphStyle.textAlignment = kCTJustifiedTextAlignment;
paragraphStyle.lineBreakMode = kCTLineBreakByWordWrapping;
paragraphStyle.firstLineHeadIndent = 30.f; // indentation for first line
paragraphStyle.lineSpacing = 3.f; // increase space between lines by 3 points
[attrStr setParagraphStyle:paragraphStyle];

// Change the color and bold of only one part of the string
[attrStr setTextColor:[UIColor redColor] range:NSMakeRange(10,3)];
[attrStr setTextBold:YES range:NSMakeRange(10,8)];

// Add a link to a given portion of the string
[attrStr setLink:someNSURL range:NSMakeRange(8,20)];

There is also a category for NSTextCheckingResult that adds the extendedURL property. This property returns the same value as the URL value for standard link cases, and return a formatted Maps URL for NSTextCheckingTypeAddress link types, that will open Google Maps in iOS version before 6.0 and the Apple's Maps application in iOS 6.0 and later.

OHASMarkupParsers and simple markup to build your attributed strings easily

The library also comes with very simple tag parsers to help you build NSAttributedStrings easily using very simple tags.

  • the class OHASBasicHTMLParser can parse simple HTML tags like <b> and <u> to make bold and underlined text, change the font color using <font color='…'>, etc

  • the class OHASBasicMarkupParser can parse simple markup like *bold text*, _underlined text_ and change the font color using markup like {red|some red text} or {#ff6600|Yeah}.

      // Example 1: parse HTML in attributed string
      basicMarkupLabel.attributedText = [OHASBasicHTMLParser attributedStringByProcessingMarkupInAttributedString:basicMarkupLabel.attributedText];
    
      // Example 2: parse basic markup in string
      NSAttributedString* as = [OHASBasicMarkupParser attributedStringByProcessingMarkupInString:@"Hello *you*!"];
    
      // Example 3: //process markup in-place in a mutable attributed string
      NSMutableAttributedString* mas = [NSMutableAttributedString attributedStringWithString:@"Hello *you*!"];
      [OHASBasicMarkupParser processMarkupInAttributedString:mas];
    

Note that OHASBasicHTMLParser is intended to be a very simple tool only to help you build attributed string easier: this is not intended to be a real and complete HTML interpreter, and will never be. For improvements of this feature, like adding other tags or markup languages, refer to issue #88)

UIAppearance support

The OHAttributedLabel class support the UIAppearance proxy API (available since iOS5). See selectors and properties marked using the UI_APPEARANCE_SELECTOR in the header.

This means that if you are targetting iOS5, you can customize all of your OHAttributedLabel links color and underline style to fit your application design, only in one call at the beginning of your application, instead of having to customize these for each instance.

For example, your could implement this in your application:didFinishLoadingWithOptions: delegate method to make all your OHAttributedLabel instances in your whole app display links in green and without underline instead of the default underlined blue:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [ [OHAttributedLabel appearance] setLinkColor:[UIColor colorWithRed:0.0 green:0.4 blue:0.0 alpha:1.0] ];
    [ [OHAttributedLabel appearance] setLinkUnderlineStyle:kCTUnderlineStyleNone ];
    return YES;
}

How to use in your project

There are three possible methods to include these classes in your project:

  1. Using Cocoapods:

    • add pod "OHAttributedLabel" to your Podfile
  2. Include OHAttributedLabel in your project:

    • Include the OHAttributedLabel.xcodeproj project in your Xcode4 workspace
    • Build this OHAttributedLabel.xcodeproj project once for the "iOS Device" (not the simulator) (1)
    • Add libOHAttributedLabel.a and CoreText.framework to your "Link Binary With Libraries" Build Phase of your app project.
    • Select the libOHAttributedLabel.a that has just been added to your app project in your Project Navigator on the left, and change the "Location" dropdown in the File Inspector to "Relative to Build Products" (1)
    • Add the -ObjC flag in the "Other Linker Flags" Build Setting (if not present already)
  3. Add libOHAttributedLabel.a and headers in your project

    • cd OHAttributedLabel
    • make clean && make (nb. rvm users may need to CC= && make clean && make)
    • copy the contents of the build/Release-Combined directory to you project (eg. ThirdParty/OHAttributedLabel)
    • Add libOHAttributedLabel.a and CoreText.framework to your "Link Binary With Libraries" Build Phase of your app project.
    • Add the OHAttributedLabel headers to your "Header Search Path" in Build Settings (eg. "$(SRCROOT)/ThirdParty/OHAttributedLabel/include/**")
    • Add the -ObjC flag in the "Other Linker Flags" Build Setting (if not present already)

Then in your application code, when you want to make use of OHAttributedLabel methods, you only need to import the headers with #import <OHAttributedLabel/OHAttributedLabel.h> or #import <OHAttributedLabel/NSAttributedString+Attributes.h> etc.

(1) Note: These two steps are only necessary to avoid a bug in Xcode4 that would otherwise make Xcode fail to detect implicit dependencies between your app and the lib.

For more details and import/linking troubleshooting, please see the dedicated page.

Sample code & Other documentation

There is no explicit docset or documentation of the class yet sorry (never had time to write one), but

  • The method names should be self-explanatory (hopefully) as I respect the standard ObjC naming conventions.
  • There are doxygen/javadoc-like documentation in the headers that should also help you describe the methods
  • The provided example ("AttributedLabel Example.xcworkspace") should also demonstrate quite every typical usages — including justifying the text, dynamically changing the style/attributes of a range of text, adding custom links, make special links with a custom behavior (like catching @mention and #hashtags), and customizing the appearance/color of links.

License & Credits

OHAttributedLabel is published under the MIT license. It has been created and developped by me (O.Halligon), but I'd like to thank all the contributors too, including @mattjgalloway, @stigi and @jparise among others.

ChangeLog — Revisions History

The ChangeLog is maintained as a wiki page accessible here.

Projects that use this class

Here is a non-exhaustive list of the projects that use this class (for those who told me about it) Feel free to contact me if you use this class so we can cross-reference our projects and quote your app in this dedicated wiki page!

More Repositories

1

OHHTTPStubs

Stub your network requests easily! Test your apps with fake network data and custom response time, response code and headers!
Objective-C
5,039
star
2

Reusable

A Swift mixin for reusing views easily and in a type-safe way (UITableViewCells, UICollectionViewCells, custom UIViews, ViewControllers, Storyboards…)
Swift
2,999
star
3

Dip

Simple Swift Dependency container. Use protocols to resolve your dependencies and avoid singletons / sharedInstances!
Swift
977
star
4

UIImage-Resize

Category to add some resizing methods to the UIImage class, to resize it to a given CGSize — or fit in a CGSize keeping aspect ratio
Objective-C
352
star
5

OHAutoNIBi18n

Automate the Localization/Translation of your XIB & interface without any additional code nor IBOutlet!
Objective-C
120
star
6

OHAttributedStringAdditions

NSAttributedString Additions that add convenience methods to manipulate attributed strings easily
Objective-C
107
star
7

SourceryTemplates

Some templates to use for Code Generation in Swift with http://github.com/krzysztofzablocki/Sourcery
HTML
99
star
8

OHGridView

View that display cells as a grid. Uses quite the same API as UITableView
Objective-C
71
star
9

OHPDFImage

A library to easily load PDF files as UIImages
Objective-C
56
star
10

Dip-UI

UI Extensions for https://github.com/AliSoftware/Dip
Swift
48
star
11

OHSwipeWheel

A widget to choose between multiple values by swiping an horizontal wheel. This is kinda like a UIPickerView but rolling horizontally and that takes much less space
Objective-C
42
star
12

pprof

Ruby Gem to list, filter, search and print Provisioning Profiles files
Ruby
39
star
13

Xcode-Utils

A set of useful templates, macros, etc. to use with the Apple Developer Tools
Objective-C
32
star
14

OpeningHours

A small iOS app to keep the list of Opening Hours for your local shops you're used to go to
Swift
27
star
15

OHActionSheet

UIActionSheet subclass that uses blocks to handle its callback (which make the code much more easier and readable)
Objective-C
27
star
16

OHStackView

This class automatically stack its subviews and relayout them when one of them change its size.
Objective-C
25
star
17

OHAlertView-OHActionSheet

This repo is obsolete. Use OHAlertView and OHActionSheet repos now.
Objective-C
21
star
18

OHURLLoader

Class that uses blocks (new to iOS4/OSX 10.6) to make URL requests/downloads much more easier
Objective-C
19
star
19

OHAlertView

UIAlertView subclass that uses blocks to handle its callback (which make the code much more easier and readable)
Objective-C
16
star
20

AliJSONRPC

A JSON-RPC Framework for Cocoa. Supports JSON-RPC 1.0, 1.1 and 2.0
Objective-C
13
star
21

alisoftware.github.io

AliSoftware's Blog "Crunchy Development": making Swift Magic ✨
SCSS
12
star
22

generate-enum-allvalues

Automatically generate a `static let allValues` for your Swift enums
Swift
8
star
23

SWPromisesDemo

A demo project implementing the StarWars API (swapi.co) in Swift with PromiseKit
Swift
8
star
24

FunctionalVCDemo

Demo for the Functional ViewControllers concept in RxSwift
Swift
8
star
25

MagicSwiftNoStrings

Demo project demonstrate some nice patterns to get rid of String-based API using enums, mixins and SwiftGen
Swift
8
star
26

CodeGen-Workshop

This is the repository used for my SwiftAveiro'19 Workshop about Code Generation
Swift
6
star
27

FormWorkflow

A sample project to demonstrate how to use Promises to describe a workflow of Screens/ViewControllers
Swift
6
star
28

ObjcSwitch

A category to allow you to use the "switch/case"-like syntax with NSObjects (and not just integers/enums!)
Objective-C
6
star
29

swift-syntax-linter-demo

A demo project on how to use SwiftSyntax to implement a simple linter detecting specific call sites of a function in your source code
Swift
6
star
30

KeyPathObserver

Execute blocks when a given property changes (this is KVO, the block-style way)
Objective-C
5
star
31

talks

My talks at conferences
5
star
32

CodeGenDemo

Demo project to show the advantages of Code Generation with SwiftGen & Sourcery
Swift
4
star
33

AliSoftware

3
star
34

SwiftDependencyInjectionTest

A test project to play around and explore some Dependency Injection ideas in Swift — This was the POC that led to Dip
Swift
3
star
35

banana-crumb-muffins

This is the recipe for Banana Crumb Muffins, presented as a GitHub repository (one commit for each step of the recipe). Just for fun.
2
star
36

TVShowOrganizer

Ruby
2
star
37

XCAssetsSample

This sample project try to expose a complex case of using multiple assets with multiple targets. Originally created to test CocoaPods/CocoaPods#3263
Objective-C
2
star
38

xcodeplugin

Tools to generate dvtplugin / xcodeplugins especially for PLIST-files structure definitions
Shell
2
star