我有一个UITextView
,它有一个NSAttributedString
,每行之间有两个换行符。我试图在textview中突出显示一行。我可以简单地在textview中突出显示一个句子,而不会有任何问题。但是,我需要突出显示从行首(textview的左侧)到行尾(textview的右侧)的句子在UITextView中突出显示一行
我已经使用以下代码来突出显示一行从此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)];
}
}];
您的文字是否始终是购物清单,中间是否与这些回车符一致? – Wain
@Wain不是购物清单,而是句子,中心与两个回车对齐。 –
请问,您如何决定要突出显示哪条线? – Happiehappie