Convert Figma logo to code with AI

ibireme logoYYText

Powerful text framework for iOS to display and edit rich text.

8,846
1,691
8,846
506

Top Related Projects

[EXPERIMENTAL] Graceful morphing effects for UILabel written in Swift.

A drop-in replacement for UILabel that supports attributes, data detectors, links, and more

19,955

A Swift Autolayout DSL for iOS & OS X

The better way to deal with JSON data in Swift.

40,982

Elegant HTTP Networking in Swift

Quick Overview

YYText is a powerful text rendering and layout engine for iOS. It provides a high-performance alternative to Apple's TextKit, offering advanced text rendering capabilities, rich text editing features, and asynchronous rendering for improved performance.

Pros

  • High performance text rendering and layout
  • Rich text editing capabilities with support for various attributes
  • Asynchronous rendering for smooth scrolling and improved user experience
  • Extensive customization options for text containers, exclusion paths, and attachments

Cons

  • Limited to iOS platform, not available for other operating systems
  • Steeper learning curve compared to native UIKit text components
  • May require more setup and configuration for basic use cases
  • Documentation is primarily in Chinese, which may be challenging for non-Chinese speakers

Code Examples

  1. Creating a YYLabel with attributed text:
YYLabel *label = [[YYLabel alloc] initWithFrame:CGRectMake(10, 10, 300, 200)];
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"Hello, YYText!"];
[text setColor:[UIColor blueColor] range:NSMakeRange(0, 5)];
[text setFont:[UIFont boldSystemFontOfSize:18] range:NSMakeRange(7, 6)];
label.attributedText = text;
[self.view addSubview:label];
  1. Adding a custom highlight to text:
YYTextHighlight *highlight = [YYTextHighlight new];
highlight.color = [UIColor redColor];
highlight.backgroundColor = [UIColor yellowColor];
[text setTextHighlight:highlight range:NSMakeRange(0, 5)];

label.highlightTapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
    NSLog(@"Tapped on highlighted text: %@", [text.string substringWithRange:range]);
};
  1. Using asynchronous rendering:
YYLabel *label = [[YYLabel alloc] initWithFrame:CGRectMake(10, 10, 300, 0)];
label.displaysAsynchronously = YES;
label.ignoreCommonProperties = YES;
label.fadeOnAsynchronouslyDisplay = NO;
label.fadeOnHighlight = NO;

NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"Long text content..."];
// Add attributes to text...

label.attributedText = text;
[label sizeToFit];
[self.view addSubview:label];

Getting Started

  1. Install YYText using CocoaPods by adding the following to your Podfile:

    pod 'YYText'
    
  2. Import YYText in your Objective-C file:

    #import <YYText/YYText.h>
    
  3. Create a simple YYLabel:

    YYLabel *label = [[YYLabel alloc] initWithFrame:CGRectMake(10, 10, 300, 100)];
    label.text = @"Hello, YYText!";
    [self.view addSubview:label];
    
  4. Run pod install in your project directory and open the .xcworkspace file to build and run your project.

Competitor Comparisons

[EXPERIMENTAL] Graceful morphing effects for UILabel written in Swift.

Pros of LTMorphingLabel

  • Focuses on text animation and morphing effects, providing visually appealing transitions
  • Offers a variety of pre-built morphing effects, making it easy to implement dynamic text changes
  • Lightweight and specifically designed for label animations

Cons of LTMorphingLabel

  • Limited to label animations, lacking the extensive text handling capabilities of YYText
  • Does not provide advanced text layout or rich text editing features
  • May have higher performance overhead for simple text displays due to animation calculations

Code Comparison

LTMorphingLabel:

let label = LTMorphingLabel()
label.text = "Hello"
label.morphingEffect = .evaporate
label.text = "World"

YYText:

YYLabel *label = [YYLabel new];
label.attributedText = [[NSAttributedString alloc] initWithString:@"Hello World" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
label.textVerticalAlignment = YYTextVerticalAlignmentCenter;

LTMorphingLabel excels in creating animated text transitions, while YYText offers more comprehensive text handling and layout capabilities. LTMorphingLabel is ideal for projects requiring eye-catching label animations, whereas YYText is better suited for complex text rendering and editing tasks.

A drop-in replacement for UILabel that supports attributes, data detectors, links, and more

Pros of TTTAttributedLabel

  • Lightweight and easy to integrate
  • Supports automatic data detection (e.g., links, phone numbers)
  • Well-established and widely used in the iOS community

Cons of TTTAttributedLabel

  • Limited customization options compared to YYText
  • Lacks advanced text rendering features
  • Less frequent updates and maintenance

Code Comparison

TTTAttributedLabel:

TTTAttributedLabel *label = [[TTTAttributedLabel alloc] initWithFrame:CGRectZero];
label.font = [UIFont systemFontOfSize:14];
label.textColor = [UIColor darkGrayColor];
label.lineBreakMode = NSLineBreakByWordWrapping;
label.numberOfLines = 0;

YYText:

YYLabel *label = [YYLabel new];
label.font = [UIFont systemFontOfSize:14];
label.textColor = [UIColor darkGrayColor];
label.numberOfLines = 0;
label.textContainerInset = UIEdgeInsetsMake(10, 10, 10, 10);
label.textVerticalAlignment = YYTextVerticalAlignmentCenter;

Both libraries provide similar basic functionality for creating and styling labels. However, YYText offers more advanced features and customization options, such as text container insets and vertical alignment, which are not available in TTTAttributedLabel. YYText also provides better performance for complex text rendering and animations, making it more suitable for applications with demanding text display requirements.

19,955

A Swift Autolayout DSL for iOS & OS X

Pros of SnapKit

  • Focused on auto layout constraints, making it easier to create responsive UI layouts
  • Provides a concise, chainable syntax for defining constraints
  • Widely adopted in the iOS development community with extensive documentation

Cons of SnapKit

  • Limited to layout constraints, lacking rich text rendering capabilities
  • May require additional libraries for complex text handling and styling
  • Less suitable for projects requiring advanced text manipulation

Code Comparison

SnapKit:

view.snp.makeConstraints { make in
    make.top.equalTo(superview).offset(20)
    make.left.right.equalTo(superview).inset(16)
    make.height.equalTo(44)
}

YYText:

YYTextView *textView = [YYTextView new];
textView.text = @"Hello, YYText!";
textView.font = [UIFont systemFontOfSize:16];
textView.textColor = [UIColor blackColor];
textView.textContainerInset = UIEdgeInsetsMake(10, 10, 10, 10);

Summary

SnapKit excels in creating auto layout constraints with a clean, Swift-friendly syntax, making it ideal for responsive UI design. YYText, on the other hand, focuses on rich text rendering and manipulation, offering more advanced text-related features. While SnapKit is more widely adopted for general layout purposes, YYText is better suited for projects requiring complex text handling and styling.

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 the likelihood of runtime errors
  • Lightweight and easy to integrate into Swift projects

Cons of SwiftyJSON

  • Limited to JSON parsing, while YYText offers a broader range of text-related functionalities
  • May require additional libraries for more complex text rendering or manipulation tasks
  • Less suitable for projects that require advanced text layout and styling capabilities

Code Comparison

SwiftyJSON:

let json = JSON(data: dataFromNetworking)
if let name = json["user"]["name"].string {
    // Do something with name
}

YYText:

YYTextView *textView = [YYTextView new];
textView.text = @"Hello, YYText!";
textView.font = [UIFont systemFontOfSize:16];
[self.view addSubview:textView];

Summary

SwiftyJSON excels in JSON parsing for Swift projects, offering a type-safe and easy-to-use API. However, it's limited to JSON handling and lacks the extensive text rendering capabilities of YYText. YYText, on the other hand, provides a comprehensive solution for text-related tasks in iOS applications, including advanced layout and styling options. The choice between the two depends on the specific requirements of your project, with SwiftyJSON being ideal for JSON-centric tasks and YYText better suited for complex text manipulation and display needs.

40,982

Elegant HTTP Networking in Swift

Pros of Alamofire

  • Comprehensive networking library for HTTP networking in Swift
  • Extensive documentation and active community support
  • Built-in features like request/response serialization and authentication

Cons of Alamofire

  • Focused solely on networking, lacks text rendering capabilities
  • May be overkill for simple networking tasks
  • Steeper learning curve for beginners compared to YYText

Code Comparison

YYText (Text rendering):

let text = NSMutableAttributedString(string: "Hello, World!")
text.yy_setColor(.red, range: NSRange(location: 0, length: 5))
text.yy_setFont(UIFont.boldSystemFont(ofSize: 18), range: NSRange(location: 7, length: 5))

Alamofire (Networking):

AF.request("https://api.example.com/data").responseJSON { response in
    switch response.result {
    case .success(let value):
        print("JSON: \(value)")
    case .failure(let error):
        print("Error: \(error)")
    }
}

While YYText excels in text rendering and manipulation, Alamofire is a powerful networking library. YYText offers more flexibility for text-related tasks, while Alamofire provides robust networking capabilities. The choice between the two depends on the specific requirements of your project.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

YYText

License MIT  Carthage compatible  CocoaPods  CocoaPods  Support  Build Status

Powerful text framework for iOS to display and edit rich text.
(It's a component of YYKit)

Features

  • UILabel and UITextView API compatible
  • High performance asynchronous text layout and rendering
  • Extended CoreText attributes with more text effects
  • Text attachments with UIImage, UIView and CALayer
  • Custom highlight text range to allow user interact with
  • Text parser support (built in markdown/emoticon parser)
  • Text container path and exclusion paths support
  • Vertical form layout support (for CJK text)
  • Image and attributed text copy/paste support
  • Attributed text placeholder support
  • Custom keyboard view support
  • Undo and redo control
  • Attributed text archiver and unarchiver support
  • Multi-language and VoiceOver support
  • Interface Builder support
  • Fully documented

Architecture

YYText vs TextKit

Text Attributes

YYText supported attributes

Demo Attribute Name Class
TextAttachment YYTextAttachment
TextHighlight YYTextHighlight
TextBinding YYTextBinding
TextShadow
TextInnerShadow
YYTextShadow
TextBorder YYTextBorder
TextBackgroundBorder YYTextBorder
TextBlockBorder YYTextBorder
TextGlyphTransform NSValue(CGAffineTransform)
TextUnderline YYTextDecoration
TextStrickthrough YYTextDecoration
TextBackedString YYTextBackedString

CoreText attributes which is supported by YYText

Demo Attribute Name Class
Font UIFont(CTFontRef)
Kern NSNumber
StrokeWidth NSNumber
StrokeColor CGColorRef
Shadow NSShadow
Ligature NSNumber
VerticalGlyphForm NSNumber(BOOL)
WritingDirection NSArray(NSNumber)
RunDelegate CTRunDelegateRef
TextAlignment NSParagraphStyle
(NSTextAlignment)
LineBreakMode NSParagraphStyle
(NSLineBreakMode)
LineSpacing NSParagraphStyle
(CGFloat)
ParagraphSpacing
ParagraphSpacingBefore
NSParagraphStyle
(CGFloat)
FirstLineHeadIndent NSParagraphStyle
(CGFloat)
HeadIndent NSParagraphStyle
(CGFloat)
TailIndent NSParagraphStyle
(CGFloat)
MinimumLineHeight NSParagraphStyle
(CGFloat)
MaximumLineHeight NSParagraphStyle
(CGFloat)
LineHeightMultiple NSParagraphStyle
(CGFloat)
BaseWritingDirection NSParagraphStyle
(NSWritingDirection)
DefaultTabInterval
TabStops
NSParagraphStyle
CGFloat/NSArray(NSTextTab)

Usage

Basic

// YYLabel (similar to UILabel)
YYLabel *label = [YYLabel new];
label.frame = ...
label.font = ...
label.textColor = ...
label.textAlignment = ...
label.lineBreakMode = ...
label.numberOfLines = ...
label.text = ...
    
// YYTextView (similar to UITextView)
YYTextView *textView = [YYTextView new];
textView.frame = ...
textView.font = ...
textView.textColor = ...
textView.dataDetectorTypes = ...
textView.placeHolderText = ...
textView.placeHolderTextColor = ...
textView.delegate = ...

Attributed text

// 1. Create an attributed string.
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"Some Text, blabla..."];
    
// 2. Set attributes to text, you can use almost all CoreText attributes.
text.yy_font = [UIFont boldSystemFontOfSize:30];
text.yy_color = [UIColor blueColor];
[text yy_setColor:[UIColor redColor] range:NSMakeRange(0, 4)];
text.yy_lineSpacing = 10;
    
// 3. Set to YYLabel or YYTextView.
YYLabel *label = [YYLabel new];
label.frame = ...
label.attributedString = text;
    
YYTextView *textView = [YYTextView new];
textView.frame = ...
textView.attributedString = text;

Text highlight

You can use some convenience methods to set text highlight:

[text yy_setTextHighlightRange:range
                       color:[UIColor blueColor]
             backgroundColor:[UIColor grayColor]
                   tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){ 
                       NSLog(@"tap text range:..."); 
                   }];

Or set the text highlight with your custom config:

// 1. Create a 'highlight' attribute for text.
YYTextBorder *border = [YYTextBorder borderWithFillColor:[UIColor grayColor] cornerRadius:3];
   
YYTextHighlight *highlight = [YYTextHighlight new];
[highlight setColor:[UIColor whiteColor]];
[highlight setBackgroundBorder:highlightBorder];
highlight.tapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
 NSLog(@"tap text range:..."); 
 // you can also set the action handler to YYLabel or YYTextView.
};
    
// 2. Add 'highlight' attribute to a range of text.
[attributedText yy_setTextHighlight:highlight range:highlightRange];
    
// 3. Set text to label or text view.
YYLabel *label = ...
label.attributedText = attributedText
    
YYTextView *textView = ...
textView.attributedText = ...
    
// 4. Receive user interactive action.
label.highlightTapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
   NSLog(@"tap text range:...");
};
label.highlightLongPressAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
   NSLog(@"long press text range:...");
};
    
@UITextViewDelegate
- (void)textView:(YYTextView *)textView didTapHighlight:(YYTextHighlight *)highlight inRange:(NSRange)characterRange rect:(CGRect)rect {
   NSLog(@"tap text range:...");
}
- (void)textView:(YYTextView *)textView didLongPressHighlight:(YYTextHighlight *)highlight inRange:(NSRange)characterRange rect:(CGRect)rect {
   NSLog(@"long press text range:...");
}

Text attachments

NSMutableAttributedString *text = [NSMutableAttributedString new];
UIFont *font = [UIFont systemFontOfSize:16];
NSMutableAttributedString *attachment = nil;
	
// UIImage attachment
UIImage *image = [UIImage imageNamed:@"dribbble64_imageio"];
attachment = [NSMutableAttributedString yy_attachmentStringWithContent:image contentMode:UIViewContentModeCenter attachmentSize:image.size alignToFont:font alignment:YYTextVerticalAlignmentCenter];
[text appendAttributedString: attachment];
	
// UIView attachment
UISwitch *switcher = [UISwitch new];
[switcher sizeToFit];
attachment = [NSMutableAttributedString yy_attachmentStringWithContent:switcher contentMode:UIViewContentModeBottom attachmentSize:switcher.size alignToFont:font alignment:YYTextVerticalAlignmentCenter];
[text appendAttributedString: attachment];
	
// CALayer attachment
CASharpLayer *layer = [CASharpLayer layer];
layer.path = ...
attachment = [NSMutableAttributedString yy_attachmentStringWithContent:layer contentMode:UIViewContentModeBottom attachmentSize:switcher.size alignToFont:font alignment:YYTextVerticalAlignmentCenter];
[text appendAttributedString: attachment];

Text layout calculation

NSAttributedString *text = ...
CGSize size = CGSizeMake(100, CGFLOAT_MAX);
YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:size text:text];
	
// get text bounding
layout.textBoundingRect; // get bounding rect
layout.textBoundingSize; // get bounding size
	
 // query text layout
[layout lineIndexForPoint:CGPointMake(10,10)];
[layout closestLineIndexForPoint:CGPointMake(10,10)];
[layout closestPositionToPoint:CGPointMake(10,10)];
[layout textRangeAtPoint:CGPointMake(10,10)];
[layout rectForRange:[YYTextRange rangeWithRange:NSMakeRange(10,2)]];
[layout selectionRectsForRange:[YYTextRange rangeWithRange:NSMakeRange(10,2)]];
	
// text layout display
YYLabel *label = [YYLabel new];
label.size = layout.textBoundingSize;
label.textLayout = layout;

Adjust text line position

// Convenience methods:
// 1. Create a text line position modifier, implements `YYTextLinePositionModifier` protocol.
// 2. Set it to label or text view.
	
YYTextLinePositionSimpleModifier *modifier = [YYTextLinePositionSimpleModifier new];
modifier.fixedLineHeight = 24;
	
YYLabel *label = [YYLabel new];
label.linePositionModifier = modifier;
	
// Fully control
YYTextLinePositionSimpleModifier *modifier = [YYTextLinePositionSimpleModifier new];
modifier.fixedLineHeight = 24;
	
YYTextContainer *container = [YYTextContainer new];
container.size = CGSizeMake(100, CGFLOAT_MAX);
container.linePositionModifier = modifier;
	
YYTextLayout *layout = [YYTextLayout layoutWithContainer:container text:text];
YYLabel *label = [YYLabel new];
label.size = layout.textBoundingSize;
label.textLayout = layout;

Asynchronous layout and rendering

// If you have performance issues,
// you may enable the asynchronous display mode.
YYLabel *label = ...
label.displaysAsynchronously = YES;
    
// If you want to get the highest performance, you should do 
// text layout with `YYTextLayout` class in background thread.
YYLabel *label = [YYLabel new];
label.displaysAsynchronously = YES;
label.ignoreCommonProperties = YES;
    
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
   // Create attributed string.
   NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"Some Text"];
   text.yy_font = [UIFont systemFontOfSize:16];
   text.yy_color = [UIColor grayColor];
   [text yy_setColor:[UIColor redColor] range:NSMakeRange(0, 4)];
 	
   // Create text container
   YYTextContainer *container = [YYTextContainer new];
   container.size = CGSizeMake(100, CGFLOAT_MAX);
   container.maximumNumberOfRows = 0;
   
   // Generate a text layout.
   YYTextLayout *layout = [YYTextLayout layoutWithContainer:container text:text];
   
   dispatch_async(dispatch_get_main_queue(), ^{
       label.size = layout.textBoundingSize;
       label.textLayout = layout;
   });
});

Text container control

YYLabel *label = ...
label.textContainerPath = [UIBezierPath bezierPathWith...];
label.exclusionPaths = 	@[[UIBezierPath bezierPathWith...];,...];
label.textContainerInset = UIEdgeInsetsMake(...);
label.verticalForm = YES/NO;
    
YYTextView *textView = ...
textView.exclusionPaths = 	@[[UIBezierPath bezierPathWith...];,...];
textView.textContainerInset = UIEdgeInsetsMake(...);
textView.verticalForm = YES/NO;

Text parser

// 1. Create a text parser
	
YYTextSimpleEmoticonParser *parser = [YYTextSimpleEmoticonParser new];
NSMutableDictionary *mapper = [NSMutableDictionary new];
mapper[@":smile:"] = [UIImage imageNamed:@"smile.png"];
mapper[@":cool:"] = [UIImage imageNamed:@"cool.png"];
mapper[@":cry:"] = [UIImage imageNamed:@"cry.png"];
mapper[@":wink:"] = [UIImage imageNamed:@"wink.png"];
parser.emoticonMapper = mapper;
	
YYTextSimpleMarkdownParser *parser = [YYTextSimpleMarkdownParser new];
[parser setColorWithDarkTheme];
    
MyCustomParser *parser = ... // custom parser
    
// 2. Attach parser to label or text view
YYLabel *label = ...
label.textParser = parser;
    
YYTextView *textView = ...
textView.textParser = parser;

Debug

// Set a shared debug option to show text layout result.
YYTextDebugOption *debugOptions = [YYTextDebugOption new];
debugOptions.baselineColor = [UIColor redColor];
debugOptions.CTFrameBorderColor = [UIColor redColor];
debugOptions.CTLineFillColor = [UIColor colorWithRed:0.000 green:0.463 blue:1.000 alpha:0.180];
debugOptions.CGGlyphBorderColor = [UIColor colorWithRed:1.000 green:0.524 blue:0.000 alpha:0.200];
[YYTextDebugOption setSharedDebugOption:debugOptions];

More examples

See Demo/YYTextDemo.xcodeproj for more examples:



Installation

CocoaPods

  1. Add pod 'YYText' to your Podfile.
  2. Run pod install or pod update.
  3. Import <YYText/YYText.h>.

Carthage

  1. Add github "ibireme/YYText" to your Cartfile.
  2. Run carthage update --platform ios and add the framework to your project.
  3. Import <YYText/YYText.h>.

Manually

  1. Download all the files in the YYText subdirectory.
  2. Add the source files to your Xcode project.
  3. Link with required frameworks:
    • UIKit
    • CoreFoundation
    • CoreText
    • QuartzCore
    • Accelerate
    • MobileCoreServices
  4. Import YYText.h.

Notice

You may add YYImage or YYWebImage to your project if you want to support animated image (GIF/APNG/WebP).

Documentation

Full API documentation is available on CocoaDocs.
You can also install documentation locally using appledoc.

Requirements

This library requires iOS 6.0+ and Xcode 8.0+.

License

YYText is released under the MIT license. See LICENSE file for details.



中文介绍

功能强大的 iOS 富文本编辑与显示框架。
(该项目是 YYKit 组件之一)

特性

  • API 兼容 UILabel 和 UITextView
  • 支持高性能的异步排版和渲染
  • 扩展了 CoreText 的属性以支持更多文字效果
  • 支持 UIImage、UIView、CALayer 作为图文混排元素
  • 支持添加自定义样式的、可点击的文本高亮范围
  • 支持自定义文本解析 (内置简单的 Markdown/表情解析)
  • 支持文本容器路径、内部留空路径的控制
  • 支持文字竖排版,可用于编辑和显示中日韩文本
  • 支持图片和富文本的复制粘贴
  • 文本编辑时,支持富文本占位符
  • 支持自定义键盘视图
  • 撤销和重做次数的控制
  • 富文本的序列化与反序列化支持
  • 支持多语言,支持 VoiceOver
  • 支持 Interface Builder
  • 全部代码都有文档注释

架构

YYText 和 TextKit 架构对比

文本属性

YYText 原生支持的属性

Demo Attribute Name Class
TextAttachment YYTextAttachment
TextHighlight YYTextHighlight
TextBinding YYTextBinding
TextShadow
TextInnerShadow
YYTextShadow
TextBorder YYTextBorder
TextBackgroundBorder YYTextBorder
TextBlockBorder YYTextBorder
TextGlyphTransform NSValue(CGAffineTransform)
TextUnderline YYTextDecoration
TextStrickthrough YYTextDecoration
TextBackedString YYTextBackedString

YYText 支持的 CoreText 属性

Demo Attribute Name Class
Font UIFont(CTFontRef)
Kern NSNumber
StrokeWidth NSNumber
StrokeColor CGColorRef
Shadow NSShadow
Ligature NSNumber
VerticalGlyphForm NSNumber(BOOL)
WritingDirection NSArray(NSNumber)
RunDelegate CTRunDelegateRef
TextAlignment NSParagraphStyle
(NSTextAlignment)
LineBreakMode NSParagraphStyle
(NSLineBreakMode)
LineSpacing NSParagraphStyle
(CGFloat)
ParagraphSpacing
ParagraphSpacingBefore
NSParagraphStyle
(CGFloat)
FirstLineHeadIndent NSParagraphStyle
(CGFloat)
HeadIndent NSParagraphStyle
(CGFloat)
TailIndent NSParagraphStyle
(CGFloat)
MinimumLineHeight NSParagraphStyle
(CGFloat)
MaximumLineHeight NSParagraphStyle
(CGFloat)
LineHeightMultiple NSParagraphStyle
(CGFloat)
BaseWritingDirection NSParagraphStyle
(NSWritingDirection)
DefaultTabInterval
TabStops
NSParagraphStyle
CGFloat/NSArray(NSTextTab)

用法

基本用法

// YYLabel (和 UILabel 用法一致)
YYLabel *label = [YYLabel new];
label.frame = ...
label.font = ...
label.textColor = ...
label.textAlignment = ...
label.lineBreakMode = ...
label.numberOfLines = ...
label.text = ...
    
// YYTextView (和 UITextView 用法一致)
YYTextView *textView = [YYTextView new];
textView.frame = ...
textView.font = ...
textView.textColor = ...
textView.dataDetectorTypes = ...
textView.placeHolderText = ...
textView.placeHolderTextColor = ...
textView.delegate = ...

属性文本

// 1. 创建一个属性文本
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"Some Text, blabla..."];
    
// 2. 为文本设置属性
text.yy_font = [UIFont boldSystemFontOfSize:30];
text.yy_color = [UIColor blueColor];
[text yy_setColor:[UIColor redColor] range:NSMakeRange(0, 4)];
text.yy_lineSpacing = 10;
    
// 3. 赋值到 YYLabel 或 YYTextView
YYLabel *label = [YYLabel new];
label.frame = ...
label.attributedString = text;
    
YYTextView *textView = [YYTextView new];
textView.frame = ...
textView.attributedString = text;

文本高亮

你可以用一些已经封装好的简便方法来设置文本高亮:

[text yy_setTextHighlightRange:range
                       color:[UIColor blueColor]
             backgroundColor:[UIColor grayColor]
                   tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){ 
                       NSLog(@"tap text range:..."); 
                   }];

或者用更复杂的办法来调节文本高亮的细节:

// 1. 创建一个"高亮"属性,当用户点击了高亮区域的文本时,"高亮"属性会替换掉原本的属性
YYTextBorder *border = [YYTextBorder borderWithFillColor:[UIColor grayColor] cornerRadius:3];
   
YYTextHighlight *highlight = [YYTextHighlight new];
[highlight setColor:[UIColor whiteColor]];
[highlight setBackgroundBorder:highlightBorder];
highlight.tapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
 NSLog(@"tap text range:..."); 
 // 你也可以把事件回调放到 YYLabel 和 YYTextView 来处理。
};
    
// 2. 把"高亮"属性设置到某个文本范围
[attributedText yy_setTextHighlight:highlight range:highlightRange];
    
// 3. 把属性文本设置到 YYLabel 或 YYTextView
YYLabel *label = ...
label.attributedText = attributedText
    
YYTextView *textView = ...
textView.attributedText = ...
    
// 4. 接受事件回调
label.highlightTapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
   NSLog(@"tap text range:...");
};
label.highlightLongPressAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
   NSLog(@"long press text range:...");
};
    
@UITextViewDelegate
- (void)textView:(YYTextView *)textView didTapHighlight:(YYTextHighlight *)highlight inRange:(NSRange)characterRange rect:(CGRect)rect {
   NSLog(@"tap text range:...");
}
- (void)textView:(YYTextView *)textView didLongPressHighlight:(YYTextHighlight *)highlight inRange:(NSRange)characterRange rect:(CGRect)rect {
   NSLog(@"long press text range:...");
}

图文混排

NSMutableAttributedString *text = [NSMutableAttributedString new];
UIFont *font = [UIFont systemFontOfSize:16];
NSMutableAttributedString *attachment = nil;
	
// 嵌入 UIImage
UIImage *image = [UIImage imageNamed:@"dribbble64_imageio"];
attachment = [NSMutableAttributedString yy_attachmentStringWithContent:image contentMode:UIViewContentModeCenter attachmentSize:image.size alignToFont:font alignment:YYTextVerticalAlignmentCenter];
[text appendAttributedString: attachment];
	
// 嵌入 UIView
UISwitch *switcher = [UISwitch new];
[switcher sizeToFit];
attachment = [NSMutableAttributedString yy_attachmentStringWithContent:switcher contentMode:UIViewContentModeBottom attachmentSize:switcher.size alignToFont:font alignment:YYTextVerticalAlignmentCenter];
[text appendAttributedString: attachment];
	
// 嵌入 CALayer
CASharpLayer *layer = [CASharpLayer layer];
layer.path = ...
attachment = [NSMutableAttributedString yy_attachmentStringWithContent:layer contentMode:UIViewContentModeBottom attachmentSize:switcher.size alignToFont:font alignment:YYTextVerticalAlignmentCenter];
[text appendAttributedString: attachment];

文本布局计算

NSAttributedString *text = ...
CGSize size = CGSizeMake(100, CGFLOAT_MAX);
YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:size text:text];
	
// 获取文本显示位置和大小
layout.textBoundingRect; // get bounding rect
layout.textBoundingSize; // get bounding size
	
 // 查询文本排版结果
[layout lineIndexForPoint:CGPointMake(10,10)];
[layout closestLineIndexForPoint:CGPointMake(10,10)];
[layout closestPositionToPoint:CGPointMake(10,10)];
[layout textRangeAtPoint:CGPointMake(10,10)];
[layout rectForRange:[YYTextRange rangeWithRange:NSMakeRange(10,2)]];
[layout selectionRectsForRange:[YYTextRange rangeWithRange:NSMakeRange(10,2)]];
	
// 显示文本排版结果
YYLabel *label = [YYLabel new];
label.size = layout.textBoundingSize;
label.textLayout = layout;

文本行位置调整

// 由于中文、英文、Emoji 等字体高度不一致,或者富文本中出现了不同字号的字体,
// 可能会造成每行文字的高度不一致。这里可以添加一个修改器来实现固定行高,或者自定义文本行位置。
  
// 简单的方法:
// 1. 创建一个文本行位置修改类,实现 `YYTextLinePositionModifier` 协议。
// 2. 设置到 Label 或 TextView。
	
YYTextLinePositionSimpleModifier *modifier = [YYTextLinePositionSimpleModifier new];
modifier.fixedLineHeight = 24;
	
YYLabel *label = [YYLabel new];
label.linePositionModifier = modifier;
	
// 完全控制:
YYTextLinePositionSimpleModifier *modifier = [YYTextLinePositionSimpleModifier new];
modifier.fixedLineHeight = 24;
	
YYTextContainer *container = [YYTextContainer new];
container.size = CGSizeMake(100, CGFLOAT_MAX);
container.linePositionModifier = modifier;
	
YYTextLayout *layout = [YYTextLayout layoutWithContainer:container text:text];
YYLabel *label = [YYLabel new];
label.size = layout.textBoundingSize;
label.textLayout = layout;

异步排版和渲染

// 如果你在显示字符串时有性能问题,可以这样开启异步模式:
YYLabel *label = ...
label.displaysAsynchronously = YES;
    
// 如果需要获得最高的性能,你可以在后台线程用 `YYTextLayout` 进行预排版: 
YYLabel *label = [YYLabel new];
label.displaysAsynchronously = YES; //开启异步绘制
label.ignoreCommonProperties = YES; //忽略除了 textLayout 之外的其他属性
    
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
   // 创建属性字符串
   NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"Some Text"];
   text.yy_font = [UIFont systemFontOfSize:16];
   text.yy_color = [UIColor grayColor];
   [text yy_setColor:[UIColor redColor] range:NSMakeRange(0, 4)];
 
   // 创建文本容器
   YYTextContainer *container = [YYTextContainer new];
   container.size = CGSizeMake(100, CGFLOAT_MAX);
   container.maximumNumberOfRows = 0;
   
   // 生成排版结果
   YYTextLayout *layout = [YYTextLayout layoutWithContainer:container text:text];
   
   dispatch_async(dispatch_get_main_queue(), ^{
       label.size = layout.textBoundingSize;
       label.textLayout = layout;
   });
});

文本容器控制

YYLabel *label = ...
label.textContainerPath = [UIBezierPath bezierPathWith...];
label.exclusionPaths = 	@[[UIBezierPath bezierPathWith...];,...];
label.textContainerInset = UIEdgeInsetsMake(...);
label.verticalForm = YES/NO;
    
YYTextView *textView = ...
textView.exclusionPaths = 	@[[UIBezierPath bezierPathWith...];,...];
textView.textContainerInset = UIEdgeInsetsMake(...);
textView.verticalForm = YES/NO;

文本解析

// 1. 创建一个解析器
	
// 内置简单的表情解析
YYTextSimpleEmoticonParser *parser = [YYTextSimpleEmoticonParser new];
NSMutableDictionary *mapper = [NSMutableDictionary new];
mapper[@":smile:"] = [UIImage imageNamed:@"smile.png"];
mapper[@":cool:"] = [UIImage imageNamed:@"cool.png"];
mapper[@":cry:"] = [UIImage imageNamed:@"cry.png"];
mapper[@":wink:"] = [UIImage imageNamed:@"wink.png"];
parser.emoticonMapper = mapper;
	
// 内置简单的 markdown 解析
YYTextSimpleMarkdownParser *parser = [YYTextSimpleMarkdownParser new];
[parser setColorWithDarkTheme];
    
// 实现 `YYTextParser` 协议的自定义解析器
MyCustomParser *parser = ... 
    
// 2. 把解析器添加到 YYLabel 或 YYTextView
YYLabel *label = ...
label.textParser = parser;
    
YYTextView *textView = ...
textView.textParser = parser;

Debug

// 设置一个全局的 debug option 来显示排版结果。
YYTextDebugOption *debugOptions = [YYTextDebugOption new];
debugOptions.baselineColor = [UIColor redColor];
debugOptions.CTFrameBorderColor = [UIColor redColor];
debugOptions.CTLineFillColor = [UIColor colorWithRed:0.000 green:0.463 blue:1.000 alpha:0.180];
debugOptions.CGGlyphBorderColor = [UIColor colorWithRed:1.000 green:0.524 blue:0.000 alpha:0.200];
[YYTextDebugOption setSharedDebugOption:debugOptions];

更多示例

查看演示工程 Demo/YYTextDemo.xcodeproj:



安装

CocoaPods

  1. 在 Podfile 中添加 pod 'YYText'。
  2. 执行 pod install 或 pod update。
  3. 导入 <YYText/YYText.h>。

Carthage

  1. 在 Cartfile 中添加 github "ibireme/YYText"。
  2. 执行 carthage update --platform ios 并将生成的 framework 添加到你的工程。
  3. 导入 <YYText/YYText.h>。

手动安装

  1. 下载 YYText 文件夹内的所有内容。
  2. 将 YYText 内的源文件添加(拖放)到你的工程。
  3. 链接以下 frameworks:
    • UIKit
    • CoreFoundation
    • CoreText
    • QuartzCore
    • Accelerate
    • MobileCoreServices
  4. 导入 YYText.h。

注意

你可以添加 YYImage 或 YYWebImage 到你的工程,以支持动画格式(GIF/APNG/WebP)的图片。

文档

你可以在 CocoaDocs 查看在线 API 文档,也可以用 appledoc 本地生成文档。

系统要求

该项目最低支持 iOS 6.0 和 Xcode 8.0。

已知问题

  • YYText 并不能支持所有 CoreText/TextKit 的属性,比如 NSBackgroundColor、NSStrikethrough、NSUnderline、NSAttachment、NSLink 等,但 YYText 中基本都有对应属性作为替代。详情见上方表格。
  • YYTextView 未实现局部刷新,所以在输入和编辑大量的文本(比如超过大概五千个汉字、或大概一万个英文字符)时会出现较明显的卡顿现象。
  • 竖排版时,添加 exclusionPaths 在少数情况下可能会导致文本显示空白。
  • 当添加了非矩形的 textContainerPath,并且有嵌入大于文本排版方向宽度的 RunDelegate 时,RunDelegate 之后的文字会无法显示。这是 CoreText 的 Bug(或者说是 Feature)。

许可证

YYText 使用 MIT 许可证,详情见 LICENSE 文件。