我想把NSString和NSMutableAttributedString合并。
在下面的代码中,我想将self.txtSearch设置为自定义粗体大小和颜色。
密码-
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
SearchViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchViewCell"];
AutoSuggestModel *autoSuggestModel = [self.autoSuggestArray objectAtIndex:indexPath.row];
if ([[autoSuggestModel type] isEqualToString:@"product"] || [[autoSuggestModel type] isEqualToString:@"category"]){
cell.lblText.text = [NSString stringWithFormat:@"%@ in %@", self.txtSearch , [autoSuggestModel label]] ;
}else{
cell.lblText.text = [autoSuggestModel label];
}
return cell;
}我可以用下面的代码做粗体的特殊字符串。但我想附加这两条线。
NSMutableAttributedString *boldString = [[NSMutableAttributedString alloc] initWithString:self.txtSearch];
NSRange boldRange = [[autoSuggestModel label] rangeOfString:self.txtSearch];
[boldString addAttribute: NSFontAttributeName value:[UIFont boldSystemFontOfSize:16] range:boldRange];
[cell.lblText setAttributedText: boldString];发布于 2015-10-17 12:17:48
粗略地看一下 documentation有一个称为“组合字符串”的部分和一个名为stringByAppendingString:的方法。
使用这种方法,它应该是难以置信的直截了当地完成你想要做的事情。
NSMutableAttributedString *boldString = [[NSMutableAttributedString alloc]
initWithString:[self.txtSearch stringByAppendingString:yourMutableString]];发布于 2015-10-17 12:22:24
更新您的方法,如
if ([[autoSuggestModel type] isEqualToString:@"product"] || [[autoSuggestModel type] isEqualToString:@"category"]){
cell.textLabel.attributedText = [self getBoldText:cell withSearch:@"search text" withAutoSuggestModel:@"autoSuggestModel"];
}else{
cell.lblText.text = [autoSuggestModel label];
}//通过以下方法检查上面的代码
-(NSMutableAttributedString*)getBoldText:(UITableViewCell*)cell withSearch:(NSString*)searchText withAutoSuggestModel:(NSString*)autoSuggestModelText{
NSString *title = [NSString stringWithFormat:@"%@ in %@", searchText,autoSuggestModelText];
cell.textLabel.text = title;
UIColor *color = [UIColor redColor];
UIFont *font = [UIFont boldSystemFontOfSize:16];
NSDictionary *attrs = @{NSForegroundColorAttributeName : color,NSFontAttributeName:font};
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithAttributedString:cell.textLabel.attributedText];
[attrStr addAttributes:attrs range:[title rangeOfString:autoSuggestModelText]];
return attrStr;}
https://stackoverflow.com/questions/33186184
复制相似问题