1, case view, such as
2. Code
TextKit01ViewController.h
#import <UIKit/UIKit.h>@interface*TextView; // text can be typeset area @property (nonatomic,strong) nstextcontainer *TextContainer; // Set Text Style -(void) Markword: (nsstring*) Word intextstorage: (nstextstorage*) textstorage; @end
Textkit01viewcontroller.m
#import "TextKit01ViewController.h"@interfaceTextkit01viewcontroller ()@end@implementationTextkit01viewcontroller- (void) viewdidload{[Super Viewdidload]; CGRect Textviewrect= Cgrectinset (Self.view.bounds,10.0,20.0); //1. Create a stored text object TextstorageNstextstorage *textstorage =[[Nstextstorage alloc] initWithString:self.textView.text]; //2. Create a text-typesetting object LayoutManagerNslayoutmanager *layoutmanager =[[Nslayoutmanager alloc] init]; //3. Create a text layout area TextContainerSelf.textcontainer =[[Nstextcontainer alloc] initWithSize:textViewRect.size]; //4, set the relationship between Textstorage and LayoutManager[Textstorage Addlayoutmanager:layoutmanager]; //5, set the relationship between LayoutManager and TextContainer[LayoutManager AddTextContainer:self.textContainer]; //6. Re-build the original TextView control[Self.textview Removefromsuperview]; Self.textview=[[Uitextview alloc] Initwithframe:textviewrect TextContainer:self.textContainer]; [Self.view AddSubview:self.textView]; //7, set the style of textstorage Chinese text[Textstorage beginediting]; Nsdictionary*attrsdic =@{nstexteffectattributename:nstexteffectletterpressstyle}; Nsmutableattributedstring*attrstr =[[Nsmutableattributedstring alloc] InitWithString:self.textView.text attributes:attrsdic]; [Textstorage SETATTRIBUTEDSTRING:ATTRSTR]; [Self Markword:@"I'm"Intextstorage:textstorage]; [Self Markword:@"I"Intextstorage:textstorage]; [Textstorage endediting]; }-(void) Markword: (NSString *) word intextstorage: (Nstextstorage *) textstorage{//1. Create Regular expression regexNsregularexpression *regex = [nsregularexpression regularexpressionwithpattern:word options:0Error:nil]; //2. Scan text in TextstorageNsarray *matches = [Regex matchesInString:self.textView.text options:0Range:nsmakerange (0, [Self.textView.text length])]; //3. Set the style for the found text content for(Nstextcheckingresult *matchinchmatches) {Nsrange Matchrange=[Match Range]; [Textstorage addattribute:nsforegroundcolorattributename Value:[uicolor Redcolor] range:matchRange]; }}- (void) didreceivememorywarning{[Super didreceivememorywarning]; //Dispose of any resources the can be recreated.}@end