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
- Add the following line to your Podfile:
- Run the command:
- Import the TTTAttributedLabel framework into your project:
pod 'TTTAttributedLabel'
pod install
import TTTAttributedLabel
Usage
To start using TTTAttributedLabel, follow these steps:
- Create an instance of TTTAttributedLabel:
- Set the attributed text for the label:
- Add the label as a subview:
let label = TTTAttributedLabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
label.attributedText = NSAttributedString(string: "Hello, World!")
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
- Github repository: https://github.com/TTTAttributedLabel/TTTAttributedLabel
- Documentation: https://nschum.github.io/TTTAttributedLabel/