我有一个UITextView,它有一个NSAttributedString,每行之间有两个换行符.我试图在textview中突出显示一行.我可以简单地在textview中突出显示一个句子而没有任何问题.但是,我需要从行的开头(textview的左侧)到行尾(textview的右侧)突出显示句子
我使用下面的代码来突出显示来自这个Github Sample的一行.由于每行都有两个换行符,我想在突出显示实际句子之后我还可以获得上一个和下一个换行符并突出显示它们.但结果并不像我想要的那样.
// 1. create some fonts UIFontDescriptor* fontDescriptor = [UIFontDescriptor preferredFontDescriptorWithTextStyle:UIFontTextStyleBody]; UIFontDescriptor* boldFontDescriptor = [fontDescriptor fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold]; UIFont* boldFont = [UIFont fontWithDescriptor:boldFontDescriptor size: 0.0]; UIFont* normalFont = [UIFont preferredFontForTextStyle:UIFontTextStyleBody]; if (!_highlightedWorld) { _highlightedWorld = @""; } // Search for the highlighted world by using regex and highlight NSString* regexStr = _highlightedWorld; NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:0 error:nil]; // Highlighted attributes (Cyan font color,Bold) NSDictionary* boldAttributes = @{ NSFontAttributeName : boldFont,NSBackgroundColorAttributeName : [UIColor cyanColor]}; //Normal attributes NSDictionary* normalAttributes = @{ NSFontAttributeName : normalFont,NSBackgroundColorAttributeName : [UIColor whiteColor] }; // If the textview has multiple matches,iterate over each match,and highlight each. [regex enumerateMatchesInString:[_backingStore string] options:0 range:searchRange usingBlock:^(NSTextCheckingResult *match,NSMatchingFlags flags,BOOL *stop){ // Highlight the actual line NSRange matchRange = [match rangeAtIndex:0]; [self addAttributes:boldAttributes range:matchRange]; // Get the newline after the highlighted sentence,and highlight it // Check if we reached the end if (matchRange.location+matchRange.length < [_backingStore string].length) { [self addAttributes:boldAttributes range:NSMakeRange(matchRange.location+matchRange.length,1)]; } // Get the newline before the highlighted sentence,and highlight it // Check if we reached the beginning if (matchRange.location != 0) { [self addAttributes:boldAttributes range:NSMakeRange(matchRange.location-1,1)]; } // 4. reset the style to the original if (NSMaxRange(matchRange)+1 < self.length) { [self addAttributes:normalAttributes range:NSMakeRange(NSMaxRange(matchRange)+1,1)]; } }];