Я использовал этот ответ, чтобы создать CGRect для определенного диапазона текста.
В этом UITextView
я установил его attributedText
(поэтому у меня есть куча стилизованного текста с разными размерами глифов).
Это отлично подходит для первой строки текста, выровненной по горизонтали, но при работе с NSTextAlignmentJustified
или NSTextAlignmentCenter
она имеет некоторые странные результаты.
Он также неправильно вычисляет, когда строки обтекают или (иногда), если есть разрыв строки \n
.
Я получаю такие вещи (это выравнивание по центру):
Вместо этого я ожидаю этого:
У этого есть разрыв строки \n
- первые два кодовых бита были выделены успешно, но последний more code for you to see
был не потому, что перенос текста не учитывается в вычислениях x, y.
Здесь моя реализация:
- (void)formatMarkdownCodeBlockWithAttributes:(NSDictionary *)attributesDict
withHighlightProperties:(NSDictionary *)highlightProperties
forFontSize:(CGFloat)pointSize
{
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"`.+?`" options:NO error:nil];
NSArray *matchesArray = [regex matchesInString:[self.attributedString string] options:NO range:NSMakeRange(0, self.attributedString.length)];
for (NSTextCheckingResult *match in matchesArray)
{
NSRange range = [match range];
if (range.location != NSNotFound) {
self.textView.attributedText = self.attributedString;
CGRect codeRect = [self frameOfTextRange:range forString:[[self.attributedString string] substringWithRange:range] forFontSize:pointSize];
UIView *highlightView = [[UIView alloc] initWithFrame:codeRect];
highlightView.layer.cornerRadius = 4;
highlightView.layer.borderWidth = 1;
highlightView.backgroundColor = [highlightProperties valueForKey:@"backgroundColor"];
highlightView.layer.borderColor = [[highlightProperties valueForKey:@"borderColor"] CGColor];
[self.contentView insertSubview:highlightView atIndex:0];
[self.attributedString addAttributes:attributesDict range:range];
//strip first and last `
[[self.attributedString mutableString] replaceOccurrencesOfString:@"(^`|`$)" withString:@" " options:NSRegularExpressionSearch range:range];
}
}
}
- (CGRect)frameOfTextRange:(NSRange)range forString:(NSString *)string forFontSize:(CGFloat)pointSize
{
self.textView.selectedRange = range;
UITextRange *textRange = [self.textView selectedTextRange];
CGRect rect = [self.textView firstRectForRange:textRange];
//These three lines are a workaround for getting the correct width of the string since I'm always using the monospaced Menlo font.
rect.size.width = ((pointSize / 1.65) * string.length) - 4;
rect.origin.x+=2;
rect.origin.y+=2;
return rect;
}
О, и в случае, если вы этого хотите, вот строка, в которую я играю:
*This* is **awesome** @mention `code` more \n `code and code` #hashtag [markdown](http://google.com) __and__ @mention2 {#FFFFFF|colored text} This**will also** work but ** will not ** **work** Also, some `more code for you to see`
Примечание: Пожалуйста, не предлагайте использовать TTTAttributedLabel
или OHAttributedLabel
.