我创建了一个自定义的tableview单元格,我想在该单元格中显示一些字符串。我从后端获取字符串,因此我不知道我需要多少标签。我尝试在一个标签中连接字符串并实现如下所示但是我希望在char"之后显示具有不同属性的字符串:"。
for (AttributesModel* attribute in model.attributes) {
NSString *attributeName = attribute.name;
attributeString = [[attributeString stringByAppendingString: attributeName] mutableCopy];
attributeString = [[attributeString stringByAppendingString: @" : "] mutableCopy];
for (NSDictionary *value in attribute.options) {
attributeString = [[attributeString stringByAppendingString: [value objectForKey:@"name"] ] mutableCopy];
attributeString = [[attributeString stringByAppendingString: @", "] mutableCopy];
}
attributeString = [[attributeString stringByAppendingString: @"\n"] mutableCopy];
}
我无法更改位于char"之后的字符串的属性:"。 有没有办法做到这一点?我可以在单元格中创建动态数量的标签,还是仅更改仅位于"之后的字符串属性:" ?
答案 0 :(得分:1)
听起来您想要更改UILabel中文本部分格式等属性。您可以通过以下方式执行此操作:
attributedText
属性设置为您的属性字符串。NSString *myString = @"This is my string";
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:myString];
NSMutableAttributedString *mutableAttributedString = [attributedString mutableCopy];
// The range of text to change, i.e. start from the 5th index
// (starting from 0 like arrays), and continue for 2 characters:
NSRange rangeOfSecondWord = NSMakeRange(5, 2);
// The list of attributes to apply to that range:
NSDictionary *myAttributes = @{
NSForegroundColorAttributeName : [UIColor redColor],
};
// Actually apply the attributes:
[mutableAttributedString setAttributes:myAttributes range:rangeOfSecondWord];
// Set the text of the label to the attributed string:
myLabel.attributedText = mutableAttributedString;
有关您可以在字典中设置的属性列表,请参阅Character Attributes reference。
由于您正在下载字符串,因此您可能事先不知道该范围。由于您将它们连接起来,以下是您可以动态查找范围的方法:
NSString *stringOne = @"My name is ";
NSString *stringTwo = @"John Citizen";
NSString *joinedStrings = [stringOne stringByAppendingString:stringTwo];
NSRange rangeOfStringTwo = [joinedStrings rangeOfString:stringTwo];