TTTAttributedLabel
A drop-in replacement for UILabel that supports attributes, data detectors, links, and more
Top Related Projects
UILabel drop-in replacement supporting Hashtags (#), Mentions (@) and URLs (http://) written in Swift
[EXPERIMENTAL] Graceful morphing effects for UILabel written in Swift.
A beautiful and flexible text field control implementation of "Float Label Pattern". Written in Swift.
A lightweight, pure-Swift library for downloading and caching images from the web.
The better way to deal with JSON data in Swift.
Quick Overview
TTTAttributedLabel is a drop-in replacement for UILabel that supports attributes, data detectors, links, and more. It provides a rich text label for iOS, allowing developers to easily create labels with custom styling, clickable links, and other advanced features not available in the standard UILabel.
Pros
- Easy to use as a drop-in replacement for UILabel
- Supports rich text attributes, including custom fonts, colors, and styles
- Allows for clickable links and custom link detection
- Offers data detectors for automatically identifying phone numbers, addresses, etc.
Cons
- May have performance issues with very long text or many attributes
- Some users report issues with text truncation and line breaking
- Not actively maintained (last commit was in 2019)
- Limited documentation and examples for advanced use cases
Code Examples
- Creating a basic TTTAttributedLabel:
let label = TTTAttributedLabel(frame: CGRect(x: 20, y: 20, width: 280, height: 60))
label.text = "Hello, TTTAttributedLabel!"
view.addSubview(label)
- Adding a clickable link:
label.enabledTextCheckingTypes = NSTextCheckingResult.CheckingType.link.rawValue
label.text = "Visit our website: https://example.com"
label.delegate = self
// In the delegate method:
func attributedLabel(_ label: TTTAttributedLabel!, didSelectLinkWith url: URL!) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
- Applying custom attributes:
let attributedString = NSMutableAttributedString(string: "Styled Text")
attributedString.addAttribute(.foregroundColor, value: UIColor.red, range: NSRange(location: 0, length: 6))
attributedString.addAttribute(.font, value: UIFont.boldSystemFont(ofSize: 18), range: NSRange(location: 7, length: 4))
label.attributedText = attributedString
Getting Started
To use TTTAttributedLabel in your project:
-
Install via CocoaPods by adding to your Podfile:
pod 'TTTAttributedLabel'
-
Import the library in your Swift file:
import TTTAttributedLabel
-
Create and use a TTTAttributedLabel:
let label = TTTAttributedLabel(frame: CGRect(x: 20, y: 20, width: 280, height: 60)) label.text = "Your text here" view.addSubview(label)
Competitor Comparisons
UILabel drop-in replacement supporting Hashtags (#), Mentions (@) and URLs (http://) written in Swift
Pros of ActiveLabel.swift
- Written in Swift, providing better performance and type safety
- Supports custom patterns for detecting and highlighting text
- Offers a more modern and lightweight implementation
Cons of ActiveLabel.swift
- Less mature and potentially less stable than TTTAttributedLabel
- May have fewer features and customization options
- Limited to iOS platforms, while TTTAttributedLabel supports both iOS and macOS
Code Comparison
TTTAttributedLabel:
TTTAttributedLabel *label = [[TTTAttributedLabel alloc] initWithFrame:CGRectZero];
label.font = [UIFont systemFontOfSize:14];
label.textColor = [UIColor darkGrayColor];
label.lineBreakMode = NSLineBreakByWordWrapping;
label.numberOfLines = 0;
ActiveLabel.swift:
let label = ActiveLabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.font = UIFont.systemFont(ofSize: 14)
label.textColor = .darkGray
Both libraries provide similar basic functionality for creating and configuring labels. However, ActiveLabel.swift offers a more concise and Swift-native syntax, while TTTAttributedLabel provides a more established Objective-C implementation with potentially more extensive features and platform support.
[EXPERIMENTAL] Graceful morphing effects for UILabel written in Swift.
Pros of LTMorphingLabel
- Offers dynamic text animations and morphing effects
- Supports various animation styles (e.g., evaporate, fall, pixelate)
- Lightweight and easy to integrate into iOS projects
Cons of LTMorphingLabel
- Limited to basic label functionality without rich text support
- May have performance issues with long text or frequent updates
- Less customization options for text styling compared to TTTAttributedLabel
Code Comparison
LTMorphingLabel:
let label = LTMorphingLabel()
label.text = "Hello, World!"
label.morphingEffect = .evaporate
label.morphingDuration = 0.5
TTTAttributedLabel:
TTTAttributedLabel *label = [[TTTAttributedLabel alloc] initWithFrame:CGRectZero];
label.font = [UIFont systemFontOfSize:14];
label.textColor = [UIColor darkGrayColor];
label.lineBreakMode = NSLineBreakByWordWrapping;
label.numberOfLines = 0;
LTMorphingLabel focuses on text animation effects, making it ideal for creating eye-catching UI elements. TTTAttributedLabel, on the other hand, provides more comprehensive text styling and interaction capabilities, suitable for complex text layouts and link handling in iOS applications.
A beautiful and flexible text field control implementation of "Float Label Pattern". Written in Swift.
Pros of SkyFloatingLabelTextField
- Provides a floating label effect for text fields, enhancing user experience
- Offers customizable error states and messages
- Supports right-to-left languages
Cons of SkyFloatingLabelTextField
- Limited to text field functionality, unlike TTTAttributedLabel's broader label capabilities
- May require more setup and configuration for basic use cases
- Potentially higher performance overhead due to animation effects
Code Comparison
SkyFloatingLabelTextField:
let textField = SkyFloatingLabelTextField(frame: CGRect(x: 10, y: 10, width: 200, height: 45))
textField.placeholder = "Email"
textField.title = "Email"
textField.errorMessage = "Invalid email"
TTTAttributedLabel:
TTTAttributedLabel *label = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(10, 10, 200, 50)];
label.font = [UIFont systemFontOfSize:14];
label.textColor = [UIColor darkGrayColor];
label.lineBreakMode = NSLineBreakByWordWrapping;
label.numberOfLines = 0;
SkyFloatingLabelTextField focuses on creating interactive and visually appealing text input fields with floating labels and error handling. TTTAttributedLabel, on the other hand, provides a more versatile solution for creating rich text labels with support for various text attributes and link detection. The choice between the two depends on the specific requirements of your project, whether you need enhanced text input fields or advanced label customization.
A lightweight, pure-Swift library for downloading and caching images from the web.
Pros of Kingfisher
- Specialized for image downloading and caching
- Supports multiple sources (URL, data, asset)
- Offers advanced features like image processing and prefetching
Cons of Kingfisher
- Limited to image handling, not suitable for general text attributes
- May be overkill for simple text-based UI elements
- Steeper learning curve for basic image display tasks
Code Comparison
Kingfisher:
let url = URL(string: "https://example.com/image.jpg")
imageView.kf.setImage(with: url)
TTTAttributedLabel:
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:@"Hello, World!" attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14]}];
label.attributedText = attributedString;
Summary
Kingfisher excels in image handling and caching, offering a comprehensive solution for image-related tasks in iOS apps. It's ideal for projects heavily focused on image display and management. TTTAttributedLabel, on the other hand, specializes in rich text formatting and display, making it more suitable for text-centric UI elements. While Kingfisher provides powerful image capabilities, it may be excessive for simple text-based interfaces. TTTAttributedLabel offers more flexibility in text styling but lacks advanced image handling features.
The better way to deal with JSON data in Swift.
Pros of SwiftyJSON
- Specifically designed for JSON parsing in Swift, offering a more streamlined and Swift-friendly API
- Provides type-safe access to JSON data, reducing runtime errors
- Supports chaining syntax for easier nested data access
Cons of SwiftyJSON
- Limited to JSON parsing, while TTTAttributedLabel offers rich text formatting capabilities
- May require additional setup for more complex data structures
- Not as versatile for UI-related tasks compared to TTTAttributedLabel
Code Comparison
SwiftyJSON:
let json = JSON(data: dataFromNetworking)
if let name = json["user"]["name"].string {
print(name)
}
TTTAttributedLabel:
TTTAttributedLabel *label = [[TTTAttributedLabel alloc] initWithFrame:CGRectZero];
label.font = [UIFont systemFontOfSize:14];
label.textColor = [UIColor darkGrayColor];
label.lineBreakMode = NSLineBreakByWordWrapping;
label.numberOfLines = 0;
Summary
SwiftyJSON is a specialized library for JSON parsing in Swift, offering type-safe and easy-to-use methods for handling JSON data. It excels in simplifying JSON operations but is limited to this specific task. TTTAttributedLabel, on the other hand, is an Objective-C library focused on rich text formatting and display in iOS applications. It provides more versatility for UI-related tasks but lacks the JSON parsing capabilities of SwiftyJSON. The choice between these libraries depends on the specific needs of your project: JSON handling or advanced text formatting.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
TTTAttributedLabel
A drop-in replacement for UILabel
that supports attributes, data detectors, links, and more
TTTAttributedLabel
is a drop-in replacement for UILabel
providing a simple way to performantly render attributed strings. As a bonus, it also supports link embedding, both automatically with NSTextCheckingTypes
and manually by specifying a range for a URL, address, phone number, event, or transit information.
Even though UILabel
received support for NSAttributedString
in iOS 6, TTTAttributedLabel
has several unique features:
- Automatic data detection
- Manual link embedding
- Label style inheritance for attributed strings
- Custom styling for links within the label
- Long-press gestures in addition to tap gestures for links
It also includes advanced paragraph style properties:
attributedTruncationToken
firstLineIndent
highlightedShadowRadius
highlightedShadowOffset
highlightedShadowColor
lineHeightMultiple
lineSpacing
minimumLineHeight
maximumLineHeight
shadowRadius
textInsets
verticalAlignment
Requirements
- iOS 8+ / tvOS 9+
- Xcode 7+
Accessibility
As of version 1.10.0, TTTAttributedLabel
supports VoiceOver through the UIAccessibilityElement
protocol. Each link can be individually selected, with an accessibilityLabel
equal to its string value, and a corresponding accessibilityValue
for URL, phone number, and date links. Developers who wish to change this behavior or provide custom values should create a subclass and override accessibilityElements
.
Communication
- If you need help, use Stack Overflow. (Tag
tttattributedlabel
) - If you'd like to ask a general question, use Stack Overflow.
- If you found a bug, open an issue.
- If you have a feature request, open an issue.
- If you want to contribute, submit a pull request.
Installation
CocoaPods is the recommended method of installing TTTAttributedLabel
. Simply add the following line to your Podfile
:
# Podfile
pod 'TTTAttributedLabel'
Usage
TTTAttributedLabel
can display both plain and attributed text: just pass an NSString
or NSAttributedString
to the setText:
setter. Never assign to the attributedText
property.
// NSAttributedString
TTTAttributedLabel *attributedLabel = [[TTTAttributedLabel alloc] initWithFrame:CGRectZero];
NSAttributedString *attString = [[NSAttributedString alloc] initWithString:@"Tom Bombadil"
attributes:@{
(id)kCTForegroundColorAttributeName : (id)[UIColor redColor].CGColor,
NSFontAttributeName : [UIFont boldSystemFontOfSize:16],
NSKernAttributeName : [NSNull null],
(id)kTTTBackgroundFillColorAttributeName : (id)[UIColor greenColor].CGColor
}];
// The attributed string is directly set, without inheriting any other text
// properties of the label.
attributedLabel.text = attString;
// NSString
TTTAttributedLabel *label = [[TTTAttributedLabel alloc] initWithFrame:CGRectZero];
label.font = [UIFont systemFontOfSize:14];
label.textColor = [UIColor darkGrayColor];
label.lineBreakMode = NSLineBreakByWordWrapping;
label.numberOfLines = 0;
// If you're using a simple `NSString` for your text,
// assign to the `text` property last so it can inherit other label properties.
NSString *text = @"Lorem ipsum dolor sit amet";
[label setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
NSRange boldRange = [[mutableAttributedString string] rangeOfString:@"ipsum dolor" options:NSCaseInsensitiveSearch];
NSRange strikeRange = [[mutableAttributedString string] rangeOfString:@"sit amet" options:NSCaseInsensitiveSearch];
// Core Text APIs use C functions without a direct bridge to UIFont. See Apple's "Core Text Programming Guide" to learn how to configure string attributes.
UIFont *boldSystemFont = [UIFont boldSystemFontOfSize:14];
CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)boldSystemFont.fontName, boldSystemFont.pointSize, NULL);
if (font) {
[mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)font range:boldRange];
[mutableAttributedString addAttribute:kTTTStrikeOutAttributeName value:@YES range:strikeRange];
CFRelease(font);
}
return mutableAttributedString;
}];
First, we create and configure the label, the same way you would instantiate UILabel
. Any text properties that are set on the label are inherited as the base attributes when using the -setText:afterInheritingLabelAttributesAndConfiguringWithBlock:
method. In this example, the substring "ipsum dolar", would appear in bold, such that the label would read "Lorem ipsum dolar sit amet", in size 14 Helvetica, with a dark gray color.
IBDesignable
TTTAttributedLabel
includes IBInspectable
and IB_DESIGNABLE
annotations to enable configuring the label inside Interface Builder. However, if you see these warnings when building...
IB Designables: Failed to update auto layout status: Failed to load designables from path (null)
IB Designables: Failed to render instance of TTTAttributedLabel: Failed to load designables from path (null)
...then you are likely using TTTAttributedLabel
as a static library, which does not support IB annotations. Some workarounds include:
- Install
TTTAttributedLabel
as a dynamic framework using CocoaPods withuse_frameworks!
in yourPodfile
, or with Carthage - Install
TTTAttributedLabel
by dragging its source files to your project
Links and Data Detection
In addition to supporting rich text, TTTAttributedLabel
can automatically detect links for dates, addresses, URLs, phone numbers, transit information, and allows you to embed your own links.
label.enabledTextCheckingTypes = NSTextCheckingTypeLink; // Automatically detect links when the label text is subsequently changed
label.delegate = self; // Delegate methods are called when the user taps on a link (see `TTTAttributedLabelDelegate` protocol)
label.text = @"Fork me on GitHub! (https://github.com/mattt/TTTAttributedLabel/)"; // Repository URL will be automatically detected and linked
NSRange range = [label.text rangeOfString:@"me"];
[label addLinkToURL:[NSURL URLWithString:@"http://github.com/mattt/"] withRange:range]; // Embedding a custom link in a substring
Demo
pod try TTTAttributedLabel
...or clone this repo and build and run/test the Espressos
project in Xcode to see TTTAttributedLabel
in action. If you don't have CocoaPods installed, grab it with [sudo] gem install cocoapods
.
cd Example
pod install
open Espressos.xcworkspace
License
TTTAttributedLabel
is available under the MIT license. See the LICENSE file for more info.
Top Related Projects
UILabel drop-in replacement supporting Hashtags (#), Mentions (@) and URLs (http://) written in Swift
[EXPERIMENTAL] Graceful morphing effects for UILabel written in Swift.
A beautiful and flexible text field control implementation of "Float Label Pattern". Written in Swift.
A lightweight, pure-Swift library for downloading and caching images from the web.
The better way to deal with JSON data in Swift.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot