我需要在用户输入时使用 UITextField
将某些单词替换为粗体单词。在指定的方法中 textViewDidChange
我有:
-(void)textViewDidChange:(UITextView *)textView {
self.notepadTextView.font = [UIFont fontWithName:@"ProximaNova-Regular" size:20];
NSString *textEntryContents = [[self notepadTextView ]text];
[gCore processSpeechText:textEntryContents]; //program specific function enabling speech
...
textEntryContents = [textEntryContents stringByReplacingOccurrencesOfString:@" performance" withString:@"\n\nPerformance"];
UIFont *fontBold = [UIFont fontWithName:@"ProximaNova-Bold" size:20];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:textEntryContents];
[string addAttribute:NSFontAttributeName value:fontBold range:NSMakeRange(0,textEntryContents.length)];
self.notepadTextView.attributedText = string;
}
这会格式化用户输入的文本,以便每次键入“性能”一词时,都会开始一个新行。这效果很好。我尝试让每次输入“表演”时,都会将这个词加粗。粗体方面有效;然而,它使一切都变得大胆,而不仅仅是“性能”这个词。
如果用户输入:
“性能测试良好,但需要更多更新。”
应该发生什么:
“性能
测试良好,但需要更多更新。”
发生了什么:
“性能
测试良好,但需要更多更新。”
self.notepadTextView.attributedText = string
似乎覆盖了之前每个单词的 UIFont
更改,而且我不知道如何制作 UITextField
接受两个“self.textView.text 's”,而不需要一个覆盖另一个。另外,我不知道我可以将属性字符串范围更改为什么,因为对于键入“性能”一词的任何索引,该范围都会不断变化。
如有任何问题,请告诉我!但请帮忙!
最佳答案
使用 NSRegularExpression
(又名正则表达式),你可以这样做:
UIFont *normalFont = [UIFont fontWithName:@"HelveticaNeue" size:20];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"hey performance tested well, but needs more updating"
attributes:@{NSFontAttributeName: normalFont}];
NSError *regexError;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"Performance"
options:NSRegularExpressionCaseInsensitive error:®exError];
if (!regexError)
{
NSArray *allMatches = [regex matchesInString:[attributedString string]
options:0
range:NSMakeRange(0, [[attributedString string] length])];
UIFont *boldFont = [UIFont fontWithName:@"HelveticaNeue-Bold" size:20];
for (NSTextCheckingResult *aMatch in allMatches)
{
NSRange matchRange = [aMatch range];
[attributedString setAttributes:@{NSFontAttributeName:boldFont}
range:matchRange];
}
}
注意:我使用了 Helvetica Neue
及其粗体版本,因为我没有您的字体。
这是我曾经尝试过的示例,因此您可以将 attributedString 原始文本替换为 textEntryContents
。
有关正则表达式的更多信息,我喜欢this tutorial他们似乎很清楚。这是 Google 搜索有关 NSRegularExpression
的第一个条目之一。他们的“备忘单”可能非常方便,如果你需要更复杂的东西(我没有检查它是否需要在搜索字符串后有一个空格等),并改变模式 Performance
,在 matchesInString:options:range:
中使用类似 [NSString stringWithFormat:@"StartingRegexWithSpecialCharactersPerformanceEndingRegexWithSpecialCharacters]
的内容。
关于ios - 从用户输入的 UITextField 创建没有硬编码范围的 NSAttributedString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24415675/