標籤:c style class blog code java
1、案例視圖,如
2、代碼
TextKit01ViewController.h
#import <UIKit/UIKit.h>@interface TextKit01ViewController : UIViewController@property (nonatomic,strong) IBOutlet UITextView *textView;// 文本可以排版的地區@property (nonatomic,strong) NSTextContainer *textContainer;// 設定文本風格- (void) markWord:(NSString*)word inTextStorage:(NSTextStorage*)textStorage;@end
TextKit01ViewController.m
#import "TextKit01ViewController.h"@interface TextKit01ViewController ()@end@implementation TextKit01ViewController- (void)viewDidLoad{ [super viewDidLoad]; CGRect textViewRect = CGRectInset(self.view.bounds, 10.0, 20.0); // 1、建立儲存文字物件textStorage NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:self.textView.text]; // 2、建立文字排版對象layoutManager NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init]; // 3、建立文本排版的地區textContainer self.textContainer = [[NSTextContainer alloc] initWithSize:textViewRect.size]; // 4、設定textStorage與layoutManager的關係 [textStorage addLayoutManager:layoutManager]; // 5、設定layoutManager與textContainer的關係 [layoutManager addTextContainer:self.textContainer]; // 6、重新構建原來的textview控制項 [self.textView removeFromSuperview]; self.textView = [[UITextView alloc] initWithFrame:textViewRect textContainer:self.textContainer]; [self.view addSubview:self.textView]; // 7、設定textStorage中文本的風格 [textStorage beginEditing]; NSDictionary *attrsDic = @{NSTextEffectAttributeName:NSTextEffectLetterpressStyle}; NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:self.textView.text attributes:attrsDic]; [textStorage setAttributedString:attrStr]; [self markWord:@"我" inTextStorage:textStorage]; [self markWord:@"I" inTextStorage:textStorage]; [textStorage endEditing]; }-(void)markWord:(NSString *)word inTextStorage:(NSTextStorage *)textStorage{ // 1、建立Regexregex NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:word options:0 error:nil]; // 2、掃描textStorage中的文本 NSArray *matches = [regex matchesInString:self.textView.text options:0 range:NSMakeRange(0, [self.textView.text length])]; // 3、為找到的常值內容設定風格 for (NSTextCheckingResult *match in matches) { NSRange matchRange = [match range]; [textStorage addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:matchRange]; }}- (void)didReceiveMemoryWarning{ [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}@end