在我的tableview单元格中,有一个Description标签。描述文本将通过Attributed Text以单独的方法突出显示。这种方法是来自cellforRowIndexPath
&这就是为什么tableview卷轴落后很多。
我的代码
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
SearchVCCell *cell = (SearchVCCell *)[tableView dequeueReusableCellWithIdentifier:cellidentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SearchVCCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.lbl_title.text=[NSString stringWithFormat:@"%@",[arrTitle objectAtIndex:indexPath.row]];
cell.lbl_disc.text=[NSString stringWithFormat:@"%@",[arrDescription objectAtIndex:indexPath.row]];
cell.lbl_page.text=[NSString stringWithFormat:@"Page: %d",[[arrPageNumber objectAtIndex:indexPath.row]intValue]];
int p= [self highlightText:_search_bar.text :cell.lbl_disc]; //Method Call
cell.lbl_count.text=[NSString stringWithFormat:@"%d",p];
}
return cell;
}
HightText方法:
-(int) highlightText :(NSString *)srcTxt :(UILabel*)txtView {
int srcTxtLen = srcTxt.length;
int idx = 0,count=0;
while (idx<(txtView.text.length-srcTxtLen)) {
NSRange srcRange = NSMakeRange(idx, srcTxtLen);
if ([[txtView.text substringWithRange:srcRange] isEqualToString:srcTxt]) {
NSMutableAttributedString *tmpAttrTxt = [[NSMutableAttributedString alloc] initWithAttributedString:txtView.attributedText];
[tmpAttrTxt addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:srcRange];
txtView.attributedText = tmpAttrTxt;
idx += srcTxtLen;
count++;
} else {
idx++;
}
}
return count;
}
帮助我解决,提前致谢
答案 0 :(得分:1)
您可以使用此
替换您的方法调用NSMutableAttributedString * string = [[NSMutableAttributedString alloc]initWithString:cell.lbl_disc.text];
NSRange range=[cell.lbl_disc.text rangeOfString:_search_bar.text];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:range];
[self.textToSpeak setAttributedText:string];
答案 1 :(得分:0)
使用此方法:
- (NSMutableAttributedString*) setColor:(UIColor*)color forWord:(NSString*)word inText:(NSMutableAttributedString*)string {
NSUInteger count = 0, length = [string length];
NSRange range = NSMakeRange(0, length);
while(range.location != NSNotFound)
{
range = [[string string] rangeOfString:word options:0 range:range];
if(range.location != NSNotFound) {
[string setTextColor:color range:NSMakeRange(range.location, [word length])];
range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
count++;
}
}
return string;
}
并在您的tableview单元格中调用此
cell.lbl_disc.text= [self setColor:[UIColor yellowColor] forWord:_search_bar.text inText:[[NSMutableAttributedString alloc] initWithAttributedString:[NSString stringWithFormat:@"%@",[arrDescription objectAtIndex:indexPath.row]]]];