UITextView文本在文本居中时突出显示

时间:2014-10-25 01:12:03

标签: ios iphone uitextview nsattributedstring

我使用以下代码突出显示UITextView中的文字 - 每次文字更改时,我都会将其转换为NSMutableAttributedString,因此我可以将其居中,添加突出显示并设置字体。< / p>

创建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];

委托方法

-(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;

}

然而,当文本开始太长而无法放入UITextView并且光标跳到下一行时,即使没有文本,背景也会着色(见图1)。当用户点击输入按钮并跳转到下一行时也会发生同样的情况(参见图1)。但是,通过在字符串中查找所有\ n个字符的范围并将该范围的NSBackgroundColorAttributeName更改为[UIColor clearColor],我能够“覆盖”它。效果如图2所示。我尝试对所有换行符(\ r和\ r \ n)执行相同的操作,但它不起作用,所以我现在卡在UITextView除非用户不使用“回车”跳到下一行,否则我会按照自己的意愿行事。

我该如何解决这个问题? Figure 1 Figure 2

0 个答案:

没有答案