追加NSString和NSMutableAttributedString

问题描述:

我想合并NSStringNSMutableAttributedString追加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]; 
+0

请给你整个cellforrowatindevpath方法 – Jamil

+0

@ jamil65able更新 – ChenSmile

一个非常粗略的看一下NSString documentation有一个称为“组合的字符串”部分和一个叫stringByAppendingString:

使用这种方法方法,应该是令人难以置信的直向前来完成你想要什么做。

NSMutableAttributedString *boldString = [[NSMutableAttributedString alloc] 
    initWithString:[self.txtSearch stringByAppendingString:yourMutableString]]; 
+0

检查上面的代码嗨,我不能直接通过单元格中的boldString ..你可以起来根据我的代码在你的答案上注明日期,我必须更改 – ChenSmile

+0

设置可变字符串的包含方法是无关紧要的。无论是在'viewDidLoad'还是'cellForRowAtIndexPath'中都无关紧要。你需要改变你的问题到你真正想要的东西,或者需要更清楚你想要完成什么。 – Stonz2

更新你喜欢的方法波纹管

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; 

}

+0

你将如何在单元格中添加合并的字符串。请你可以更新 – ChenSmile

+0

哪里找到NSMutableAttributedString? – Jamil

+0

@ jamil65able that s self.txtSearch – ChenSmile