2015-10-17 42 views
-1

我想合併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

回答

-1

一個非常粗略的看一下NSString documentation有一個稱爲「組合的字符串」部分和一個叫stringByAppendingString:

使用這種方法方法,應該是令人難以置信的直向前來完成你想要什麼做。

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

檢查上面的代碼嗨,我不能直接通過單元格中的boldString ..你可以起來根據我的代碼在你的答案上註明日期,我必須更改 – ChenSmile

+0

設置可變字符串的包含方法是無關緊要的。無論是在'viewDidLoad'還是'cellForRowAtIndexPath'中都無關緊要。你需要改變你的問題到你真正想要的東西,或者需要更清楚你想要完成什麼。 – Stonz2

0

更新你喜歡的方法波紋管

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