首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >附加NSString和NSMutableAttributedString

附加NSString和NSMutableAttributedString
EN

Stack Overflow用户
提问于 2015-10-17 11:40:41
回答 2查看 1.5K关注 0票数 0

我想把NSStringNSMutableAttributedString合并。

在下面的代码中,我想将self.txtSearch设置为自定义粗体大小和颜色。

密码-

代码语言:javascript
复制
 - (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;
}

我可以用下面的代码做粗体的特殊字符串。但我想附加这两条线。

代码语言:javascript
复制
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];
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-10-17 12:17:48

粗略地看一下 documentation有一个称为“组合字符串”的部分和一个名为stringByAppendingString:的方法。

使用这种方法,它应该是难以置信的直截了当地完成你想要做的事情。

代码语言:javascript
复制
NSMutableAttributedString *boldString = [[NSMutableAttributedString alloc] 
    initWithString:[self.txtSearch stringByAppendingString:yourMutableString]];
票数 -1
EN

Stack Overflow用户

发布于 2015-10-17 12:22:24

更新您的方法,如

代码语言:javascript
复制
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];
   }

//通过以下方法检查上面的代码

代码语言:javascript
复制
-(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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33186184

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档