在 iOS 中从 UITextView 中删除文本

Remove text from UITextView in iOS

我想用一些文本和一个按钮制作一个 UITextView,当用户 select 这个按钮在固定时间后从 UITextView 逐字隐藏文本时。我该怎么做?

在第一个图像中,所有单词都存在,但在第二个屏幕中,一段时间后单词被一个一个地擦除为此,我正在使用计时器和调用方法

 firststring = myArray[countNew];
 NSRange range=[self.textView.text rangeOfString:firststring];
  [stringWithRTFAttributes addAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} range:range];
  [self.textView setAttributedText:stringWithRTFAttributes];
  countNew++;
 if(countNew>=count)
 {
    [timer invalidate];
    NSLog(@"Timer Stops");
 }

其中count是存储单词总数的数组,countNew是整型变量。

您可以使用 NSMutableAttributedString 并将特定单词的文本颜色更改为 clearColorbackgroundColorNSTimer 是一个很好的方法。

举个例子:

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"Dummy String" attributes:@{NSForegroundColorAttributeName: [UIColor blackColor]}];
[string addAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} range:{range of substring}];

对于一个子字符串的多次出现,您可以采用这种方法:

NSString *string = @"Dummy String";
NSArray *words = [string componentsSeparatedByString:@" "];
...  //within your scheduled/for loop:
static NSInteger location = 0;
static NSInteger index = 0;
NSRange range = NSMakeRange(location, [[words objectAtIndex:index] length]);
location += [[words objectAtIndex:index] length];
index++;

我已经解决了这个问题,用定时器调用 go 方法,这是我的代码

-(void)go
{
firststring = myArray[countNew];
 NSInteger location = location1;
 NSInteger index = index1;
NSRange range = NSMakeRange(location, [[myArray objectAtIndex:countNew] length]);
NSLog(@"my range is %@  firstString %@", NSStringFromRange(range) ,firststring);
[stringWithRTFAttributes addAttribute:NSForegroundColorAttributeName value:[UIColor clearColor] range:range];
[_textView setAttributedText:stringWithRTFAttributes];
[_textView setFont:[UIFont boldSystemFontOfSize:20]];
location1 = [[myArray objectAtIndex:countNew] length] +location +1;
index1 = index++;
countNew++;
if(countNew>=[myArray count])
 {
    [timer invalidate];

 }

}

这里location1,index1是两个long int类型的数据