TTTAttributedLabel

Description

The TTTAttributedLabel class from tttAttributedLabel is a powerful label class built on top of UITextView, which provides a simple way to display and style attributed strings, similar to UILabel. TTTAttributedLabel is highly customizable and supports features like text highlighting, link detection, and data detectors.

Features

  • Supports simple styling and formatting of attributed strings
  • Automatic link detection and support for custom link interaction
  • Support for data detectors such as phone numbers, dates, and addresses
  • Customizable appearance with support for changing font, color, and background color
  • Simple integration with Auto Layout and Interface Builder
  • High performance and memory optimization

Installation

  1. Add the following line to your Podfile:
  2. pod 'TTTAttributedLabel'
  3. Run the command:
  4. pod install
  5. Import the TTTAttributedLabel framework into your project:
  6. import TTTAttributedLabel

Usage

To start using TTTAttributedLabel, follow these steps:

  1. Create an instance of TTTAttributedLabel:
  2. let label = TTTAttributedLabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
  3. Set the attributed text for the label:
  4. label.attributedText = NSAttributedString(string: "Hello, World!")
  5. Add the label as a subview:
  6. view.addSubview(label)

TTTAttributedLabel also provides several methods and properties to customize its appearance and behavior. Some of the commonly used ones are:

  • setTextColor(_:): Set the color of the label’s text.
  • addLink(to:with:,): Add a clickable link to the label’s text.
  • setText(_:): Set the text of the label.
  • enabledTextCheckingTypes: Specify the types of data to detect (e.g., phone numbers, addresses, etc.).

Examples

Here are a few examples to showcase the capabilities of TTTAttributedLabel:

let label = TTTAttributedLabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
let text = "This is a sample text with a link. Visit our website at www.example.com."
let attributedText = NSMutableAttributedString(string: text)
let linkRange = (text as NSString).range(of: "www.example.com")
let linkAttributes: [NSAttributedString.Key: Any] = [
    .foregroundColor: UIColor.blue,
    .underlineStyle: NSUnderlineStyle.single.rawValue
]
attributedText.addAttributes(linkAttributes, range: linkRange)
label.attributedText = attributedText
label.addLink(to: URL(string: "http://www.example.com"), with: linkRange)

This code snippet creates a label with a sample text containing a link. The link is customized with blue color and underlined. Tapping the link will open the specified website.

Resources