Mar*_*man 5 iphone uitextview nsattributedstring ios
我使用以下代码突出显示我UITextView的文本 - 每次文本更改时,我将其转换为NSMutableAttributedString以便我可以将其居中,添加突出显示并设置字体。
创建 UITextView
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(40, 40, 300, 100)];
textView.center = self.view.center;
textView.font = [UIFont fontWithName:@"RopaSans-Italic" size:30];
textView.backgroundColor = [UIColor clearColor];
textView.textColor = [UIColor whiteColor];
textView.textAlignment = NSTextAlignmentCenter;
textView.text = [@"" uppercaseString];
textView.delegate = self;
[self.view addSubview:textView];
Run Code Online (Sandbox Code Playgroud)
委托方法
-(void)textViewDidChange:(UITextView *)textView{
textView.text = [textView.text uppercaseString];
NSString *string = textView.text;
NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:textView.text];
NSMutableParagraphStyle *paragrapStyle = [[NSMutableParagraphStyle alloc] init];
paragrapStyle.alignment = NSTextAlignmentCenter;
paragrapStyle.lineBreakMode = NSLineBreakByWordWrapping;
[att addAttribute:NSParagraphStyleAttributeName value:paragrapStyle range:[textView.text rangeOfString:textView.text]];
[att addAttribute:NSBackgroundColorAttributeName value:[UIColor redColor] range:[textView.text rangeOfString:textView.text]];
[att addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"RopaSans-Italic" size:30] range:[textView.text rangeOfString:textView.text]];
[att addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:[textView.text rangeOfString:textView.text]];
//Find all occurencies of newline
NSString *substring = @"\n";
NSRange searchRange = NSMakeRange(0,string.length);
NSRange foundRange;
while (searchRange.location < string.length) {
searchRange.length = string.length-searchRange.location;
foundRange = [string rangeOfString:substring options:nil range:searchRange];
if (foundRange.location != NSNotFound) {
[att addAttribute:NSBackgroundColorAttributeName value:[UIColor clearColor] range:foundRange];
searchRange.location = foundRange.location+foundRange.length;
} else {
break;
}
}
textView.attributedText = att;
}
Run Code Online (Sandbox Code Playgroud)
但是,当文本开始太长而无法放入UITextView并且光标跳到下一行时,即使那里没有文本,背景也会着色(参见图 1)。当用户按下回车键并跳到下一行时,也会发生同样的情况(见图 1)。但是,我能够通过查找字符串中所有 \n 字符的范围并将NSBackgroundColorAttributeName该范围的[UIColor clearColor]. 效果如图 2 所示。我尝试对所有换行符(\r 和 \r\n)执行相同的操作,但是它不起作用,所以我现在坚持使用 a UITextView,它有点作用我想要除非用户不使用“Enter”跳到下一行。
我怎样才能解决这个问题?


| 归档时间: |
|
| 查看次数: |
356 次 |
| 最近记录: |