追加NSString和NSMutableAttributedString
问题描述:
我想合并NSString
和NSMutableAttributedString
。追加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];
答
一个非常粗略的看一下NSString
documentation有一个称为“组合的字符串”部分和一个叫stringByAppendingString:
使用这种方法方法,应该是令人难以置信的直向前来完成你想要什么做。
NSMutableAttributedString *boldString = [[NSMutableAttributedString alloc]
initWithString:[self.txtSearch stringByAppendingString:yourMutableString]];
答
更新你喜欢的方法波纹管
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;
}
请给你整个cellforrowatindevpath方法 – Jamil
@ jamil65able更新 – ChenSmile